如何在Sub-Query中获取分组数据

时间:2014-06-12 09:52:45

标签: sql sql-server-2008

我有以下数据表

Id      date
-----------------------------------
1       2014-06-11 08:35:00.000
2       2014-06-11 08:35:00.000
3       2014-06-11 08:50:00.000
4       2014-06-11 08:55:00.000
5       2014-06-11 08:55:00.000

我想查询并按日期对行进行分组,并获得以下结果

 date                            Ids
----------------------------------------
2014-06-11 08:35:00.000          1,2
2014-06-11 08:50:00.000          3
2014-06-11 08:55:00.000          4,5

为此我写了一个查询

SELECT dateadd(millisecond, - datepart(millisecond, EventDate) ,EventDate), COUNT(*),
STUFF((SELECT ',' + CAST(MetricEventId as varchar) FROM MetricEvents ME1  WHERE ME1.MetricEventId = ME.MetricEventId FOR XML PATH('')),1,1,'') FROM MetricEvents ME
GROUP BY dateadd(millisecond, - datepart(millisecond, EventDate) ,EventDate),EventUrl

但我收到错误消息

Column 'MetricEvents.MetricEventId' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

我知道它希望我通过MetricEvents.MetricEventId对查询进行分组,但这不是我的要求,因为我只想按日期对它们进行分组,如何在子查询中获取分组数据ME1.MetricEventId IN (GROUPED IDS)还是有其他选择

1 个答案:

答案 0 :(得分:1)

我想这就是你要找的东西:

SELECT t1.Date , (SELECT STUFF((SELECT ','+ cast(t2.id as nvarchar(5))
              FROM DemoTable t2 WHERE t2.Date = t1.Date
              FOR XML PATH('')), 1, 1, '')) as IDS
FROM DemoTable t1
GROUP By t1.Date

根据您的数据中是否有毫秒数,您还可以减去自己的SQL查询中的毫秒数。

Fiddle Demo