我想从开始表中获取所需的表,并另外按另一列(日期)分组。
在这里,我有什么建议吗?
答案 0 :(得分:3)
尝试一下:
DECLARE @DataSource TABLE
(
[Case] INT
,[ErrorCode] CHAR(1)
,[Date] DATE
);
INSERT INTO @DataSource ([Case], [ErrorCode], [Date])
VALUES (1, 'A', '2018-01-25')
,(1, 'B', '2018-01-15')
,(1, 'C', '2018-01-15')
,(1, 'A', '2018-01-15')
,(1, 'D', '2018-01-15')
,(1, 'A', '2018-01-15')
--
,(2, 'D', '2018-01-26')
,(2, 'A', '2018-01-26')
,(2, 'D', '2018-01-25')
,(2, 'D', '2018-01-24')
,(2, 'C', '2018-01-24');
SELECT DISTINCT DS.[Case]
,DS.[Date]
,Errors.[ErrorCode]
FROM @DataSource DS
CROSS APPLY
(
SELECT STUFF
(
(
SELECT ' / ' + [ErrorCode]
FROM @DataSource DSI
WHERE DS.[Case] = DSI.[Case]
AND DS.[Date] = DSI.[Date]
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
,1
,3
,''
)
) Errors ([ErrorCode])
ORDER BY [Case]
,[Date] DESC;
答案 1 :(得分:2)
您可以使用STRING_AGG
请尝试以下操作:
SELECT [Case], [Date], STRING_AGG (ErrorCode, '/') AS ErrorCode
FROM Table1
Group by [Case], [Date];
答案 2 :(得分:0)
请尝试这个。
SELECT distinct [Case], [Date],STUFF(
(SELECT '/' + ErrorCode
FROM Table1 as a
where a.[Case] = b.[Case] and a.Date = b.Date
ORDER BY ErrorCode
FOR XML PATH('')),1,1,'') AS ErrorCode
FROM Table1 as b
答案 3 :(得分:0)
尝试一下,
select DISTINCT [Case],[Date],
STUFF((Select '/'+ErrorCode
from Table1 T1
where T1.[Case]=T2.[Case]
And T1.[Date] =T2.[Date]
FOR XML PATH('')),1,1,'') As ErrorCode
from Table1 T2
ORDER BY [Case],[Date] DESC;
答案 4 :(得分:0)
在这种情况下,非聚集索引是成功的关键。现在需要3秒钟才能处理80k原始数据!
比我预期的要好:)