请参考下图:
答案 0 :(得分:1)
创建你的表taro:
SELECT * INTO taro
FROM
(
SELECT 1111 AS [C no.], 'ken' AS [Name], 'shiro' AS Item, '3/3/2000 12:22' AS [Date], '$25' AS Amount
UNION ALL
SELECT 1111 AS [C no.], 'ken' AS Name, 'aeshte' AS Item, '3/3/2000 12:22' AS [Date], '$25' AS Amount
UNION ALL
SELECT 1111 AS [C no.], 'ken' AS Name, 'taro' AS Item, '3/3/2000 12:22' AS [Date], '$25' AS Amount
UNION ALL
SELECT 2222,'yakumo','tesen','3/4/2000 12:22','$22'
UNION ALL
SELECT 2222,'yakumo','aoie','3/4/2000 12:22','$22'
UNION ALL
SELECT 3333,'kage','manase','3/5/2000 12:22','$21'
) A
按列对其进行分组,并将项目放在一起,以逗号分隔
SELECT
[C No.],
Name,
[Date],
Amount,
STUFF((
SELECT ',' + A.Item
FROM taro A
WHERE A.[C no.] = B.[C no.]
AND A.Name = B.Name
AND A.[Date] = B.[Date]
AND A.[Amount] = B.[Amount]
ORDER BY item
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)'),1,1,'') AS ItemValue
FROM taro B
GROUP BY [C No.],Name,[Date],Amount
结果:
C No. Name Date Amount ItemValue
----------- ------ -------------- ------ --------------------
1111 ken 3/3/2000 12:22 $25 aeshte,shiro,taro
2222 yakumo 3/4/2000 12:22 $22 aoie,tesen
3333 kage 3/5/2000 12:22 $21 manase
答案 1 :(得分:0)
DECLARE @Table1 TABLE(CNo INT, name nvarchar(20), item nvarchar(20),Date datetime, Value INT)
INSERT INTO @Table1 VALUES (1111,'ken','shiro', GETDATE(), 25),
(1111,'ken', 'aeshte', GETDATE(), 25),
(1111,'ken', 'taro', GETDATE(), 25),
(2222,'yakumo', 'tesen', GETDATE(), 25),
(2222,'yakumo', 'aole', GETDATE(), 25),
(3333,'kage', 'manase', GETDATE(), 25)
SELECT CNo
,STUFF((SELECT ', ' + CAST((item) AS VARCHAR(10)) [text()]
FROM @Table1
WHERE CNo = t.CNo and date = t.Date and Value = t.Value and name = t.name
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ') Item,
date, value, name
FROM @Table1 t
GROUP BY CNo, Date, value, name