按不同值分组

时间:2012-01-04 14:54:47

标签: sql sql-server group-by

在得到一些帮助(MSChart - Forcing a line chart to draw from the Origin)之后,我设法将以下MSSQL查询放在一起用于折线图。

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

但是,我有一个问题。此查询返回如下内容:

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

这意味着我每天都会得到一个读数,而事实上我只需要为每个不同的值提供一行。我希望第一次出现,在每种情况下,所以对于上面的例子,我希望我的查询返回:

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

我已经查看了几个似乎基于类似前提的问题,但所有的回复都是根据具体情况量身定制的(有些甚至使用LIKE来挑选出请求的结果),而且似乎没有适合这个。当然,它们也很难适应我已经拥有的查询。

有什么想法吗?提前谢谢。

编辑:对于狡猾的桌子,对不起,我的第一次尝试更糟糕。

1 个答案:

答案 0 :(得分:2)

试试这个。你已经完成了很难的部分。您只需要在Value上进行分组,然后获得与之关联的第一个(MINDate

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;