¿Cómo puedo obtener datos agrupados en Sub-Query?

I have Table with below data

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

I want to query and group the row by date and get below result

 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

for that I have wrote a query

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

but I am getting error message saying

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

I know it wants me to group my query by MetricEvents.MetricEventId as well but that's not my requirement as I want to group them only by date, how can I get my grouped data in my sub query something likeME1.MetricEventId IN (GROUPED IDS) or is there any alternative

preguntado el 12 de junio de 14 a las 10:06

do you also required MetricEventId anywhere in your data -

1 Respuestas

Supongo que esto es lo que estás buscando:

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

Depending on if you have milliseconds in your data, you can also subtract the milliseconds as in your own SQL query.

Demostración de violín

Respondido el 12 de junio de 14 a las 11:06

+1 for Fiddle Demo, I thought about it that way but I had other confusions on my mind, its very much clear now - Syed Waqas

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.