假如一个sql表里有这些数据 ,把日期相同的放在同一行里.用什么办法

003765 2011.08.01 18:01
003765 2011.08.02 07:57
003765 2011.08.01 07:57
003765 2011.08.01 12:01
003765 2011.08.01 12:55
003765 2011.08.03 12:00
003765 2011.08.02 12:00
003765 2011.08.02 12:54
003765 2011.08.02 18:09
003765 2011.08.03 07:58
003765 2011.08.03 12:55
003765 2011.08.03 18:06

SQL Server2005以上用
use Tempdb
go
--> -->

if not object_id(N'Tempdb..#') is null
drop table #
Go
Create table #([Col1] nvarchar(6),[Col2] Datetime)
Insert #
select N'003765','2011.08.01 18:01' union all
select N'003765','2011.08.02 07:57' union all
select N'003765','2011.08.01 07:57' union all
select N'003765','2011.08.01 12:01' union all
select N'003765','2011.08.01 12:55' union all
select N'003765','2011.08.03 12:00' union all
select N'003765','2011.08.02 12:00' union all
select N'003765','2011.08.02 12:54' union all
select N'003765','2011.08.02 18:09' union all
select N'003765','2011.08.03 07:58' union all
select N'003765','2011.08.03 12:55' union all
select N'003765','2011.08.03 18:06'
Go
Select
Col1,
CONVERT(VARCHAR(10),Col2,120) AS Date,
STUFF((SELECT ','+CONVERT(VARCHAR(8),Col2,8) FROM # WHERE Col1=a.Col1 AND CONVERT(VARCHAR(10),a.Col2,120)=CONVERT(VARCHAR(10),Col2,120) ORDER BY Col2 FOR XML PATH('')),1,1,'') AS Times
from # AS a
GROUP BY Col1,CONVERT(VARCHAR(10),Col2,120)

/*
Col1 Date Times
003765 2011-08-01 07:57:00,12:01:00,12:55:00,18:01:00
003765 2011-08-02 07:57:00,12:00:00,12:54:00,18:09:00
003765 2011-08-03 07:58:00,12:00:00,12:55:00,18:06:00
*/
Oracle 用WMSYS.WM_CONCAT
温馨提示:答案为网友推荐,仅供参考
大家正在搜