我有这种格式的结果集
CREATE TABLE myTable
(
CountColumn INT,
DateColumn varchar(max)
)
INSERT INTO myTable (CountColumn,DateColumn)
VALUES(212, '2013-07-15-12-25-11'), (1231,' 2013-07-20-12-25-11 , 2013-08-20-10-25-11')
, (3143, ' 2013-08-20-10-25-11'),
(783, '2013-08-20-12-25-11 , 2013-08-21-12-25-11');
现在我有一个这样的结果集(即按日期计算所有countColumn的总和)
COUNT DATE
212 2013-07-15-12-25-11
2014 2013-07-20-12-25-11
4374 2013-08-20-10-25-11
783 2013-08-21-12-25-11
答案 0 :(得分:2)
首先,创建一个内联表值分割函数(此函数 - you can pick safer or faster ones from here if you need to - 假设您的字符串永远不会包含对XML授权有问题的字符,例如>
,<
等等):
CREATE FUNCTION dbo.SplitSafeStrings
(
@List NVARCHAR(MAX),
@Delimiter NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN
( SELECT Item = LTRIM(RTRIM(y.i.value('(./text())[1]', 'nvarchar(4000)')))
FROM ( SELECT x = CONVERT(XML, '<i>'
+ REPLACE(@List, @Delimiter, '</i><i>') + '</i>').query('.')
) AS a CROSS APPLY x.nodes('i') AS y(i));
GO
现在您的查询可以是以下之一(取决于您是按日期和时间分组还是仅按日期分组):
SELECT s.Item, SUM(CountColumn)
FROM dbo.myTable AS t
CROSS APPLY dbo.SplitSafeStrings(t.DateColumn, ',') AS s
GROUP BY s.Item;
SELECT LEFT(s.Item, 10), SUM(CountColumn)
FROM dbo.myTable AS t
CROSS APPLY dbo.SplitSafeStrings(t.DateColumn, ',') AS s
GROUP BY LEFT(s.Item, 10);
分别得出这些结果:
2013-07-15-12-25-11 212
2013-07-20-12-25-11 1231
2013-08-20-10-25-11 4374
2013-08-20-12-25-11 783
2013-08-21-12-25-11 783
2013-07-15 212
2013-07-20 1231
2013-08-20 5157
2013-08-21 783
(其中没有一个与问题中的预期结果相符。如果你真的想要这些结果,你将不得不解释你是如何从样本数据中得到它们的。我怀疑你在783中犯了一个错误。 / 20 vs. 8/20。)