how to stuff date and time in SQL

橙三吉。 提交于 2020-01-22 03:20:09

问题


i am having trouble stuffing the date and time for the same item in SQL sever. Below are three simple records.

Date_Time                ID
9/6/2018 5:36:30 PM      12345
9/6/2018 6:19:02 PM      12345
9/7/2018 4:15:55 AM      12345

I would like my result to be in 1 row and the Date_Time column got stuffed followed by a comma (,).

Date_Time                                                       ID
9/6/2018 5:36:30 PM, 9/6/2018 6:19:02 PM, 9/7/2018 4:15:55 AM   12345

Would someone please point me to the right direction/link or a simple query to resolve the issue?

Thanks, XH.


回答1:


If you are using sql server 2017 or above you can use string_agg as below:

select id, string_agg(convert(varchar,DATE_Time, 22), ', ')
    from #YourTable 
    group by id

If it is below sql server 2017 you can use below query:

select id, stuff ((
    select ', ' + convert(nvarchar, date_time, 22) from #Table2 where id = t.id
    for xml path('')
    ),1,2,'') as dates
from #Table2 t
group by id



回答2:


On MySQL

SELECT id, group_concat(Date_Time) as test FROM TABLE_NAME GROUP BY ID



来源:https://stackoverflow.com/questions/58116870/how-to-stuff-date-and-time-in-sql

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