Grouping by Distinct Values

浪尽此生 提交于 2020-01-04 06:59:27

问题


I have, after some help (MSChart - Forcing a line chart to draw from the Origin), managed to put together the following MSSQL query for use in a line chart.

WITH AllDays
AS
(
    SELECT CAST('20120101' as datetime) AS days
    UNION ALL
    SELECT DATEADD(dd, 1, days)
    FROM AllDays
    WHERE DATEADD(dd, 1, days) < cast('20120201' as datetime)
)
SELECT
    MIN(ad.days) AS Date,
    ISNULL((SELECT SUM(value) FROM jobs WHERE dateinvoiced >= CAST('20120101'
    as datetime) AND dateinvoiced <= ad.days)/100,0) AS Value
FROM AllDays AS ad
LEFT JOIN jobs AS j
ON( ad.days = j.dateinvoiced )

GROUP BY ad.days

However, I have a problem. This query returns something like the below:

Date                    | Value

2012-01-01 00:00:00.000 |     0 
2012-01-02 00:00:00.000 |     0
2012-01-03 00:00:00.000 |  1234
2012-01-04 00:00:00.000 |  1234
2012-01-05 00:00:00.000 |  1234
2012-01-06 00:00:00.000 | 57312
2012-01-07 00:00:00.000 | 57312
2012-01-08 00:00:00.000 | 90812

This means that I get a reading for every single day, whereas in fact I only require one row for each distinct Value. I want the first time it appears, in every case, so for the above example I would want my query to return:

Date                    | Value

2012-01-01 00:00:00.000 |     0
2012-01-03 00:00:00.000 |  1234
2012-01-06 00:00:00.000 | 57312
2012-01-08 00:00:00.000 | 90812

I've looked through several questions that seem to be based on a similar premise, but all of the responses were very tailored to the specific situation (some even use LIKE to pick out requested results), and didn't seem to suit this. They also, of course, would be difficult to fit into the query I already have.

Any ideas? Thanks in advance.

Edit: sorry for dodgy tables, my first attempt was much worse.


回答1:


Try this. You've done the hard part already. You just need to group on Value and get the first (i.e. MIN) Date associated with it:

WITH AllDays AS (
    SELECT CAST('20120101' as datetime) AS days
    UNION ALL
    SELECT DATEADD(dd, 1, days)
    FROM AllDays
    WHERE DATEADD(dd, 1, days) < cast('20120201' as datetime)
), V AS (
  SELECT
    MIN(ad.days) AS Date,
    ISNULL((SELECT SUM(value) FROM jobs WHERE dateinvoiced >= CAST('20120101'
    as datetime) AND dateinvoiced <= ad.days)/100,0) AS Value
  FROM AllDays AS ad
  LEFT JOIN jobs AS j ON (ad.days = j.dateinvoiced)
  GROUP BY ad.days
)
SELECT MIN(Date) Date, Value
FROM V
GROUP BY Value;


来源:https://stackoverflow.com/questions/8728842/grouping-by-distinct-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!