Sql server 计算日期并在列中显示为逗号分隔的值
表格:Sql server 计算日期并在列中显示为逗号分隔的值,sql-server,sql-server-2008-r2,Sql Server,Sql Server 2008 R2,表格: CREATE TABLE test ( cola int, colb date ); insert into test values(111,'2014-3-2'); insert into test values(111,'2014-3-3'); insert into test values(111,'2014-3-2'); insert into test values(121,'2014-4-1'); insert into test values(121,'2014-4-2'
CREATE TABLE test
(
cola int,
colb date
);
insert into test values(111,'2014-3-2');
insert into test values(111,'2014-3-3');
insert into test values(111,'2014-3-2');
insert into test values(121,'2014-4-1');
insert into test values(121,'2014-4-2');
insert into test values(121,'2014-4-3');
insert into test values(121,'2014-4-4');
insert into test values(131,'2014-5-1');
insert into test values(131,'2014-5-1');
插入:
CREATE TABLE test
(
cola int,
colb date
);
insert into test values(111,'2014-3-2');
insert into test values(111,'2014-3-3');
insert into test values(111,'2014-3-2');
insert into test values(121,'2014-4-1');
insert into test values(121,'2014-4-2');
insert into test values(121,'2014-4-3');
insert into test values(121,'2014-4-4');
insert into test values(131,'2014-5-1');
insert into test values(131,'2014-5-1');
注意:我想显示在特定日期中输入的cola
。并且要计算出存在于
特定的cola
出现了colb
列。并希望显示逗号分隔的日期以及特定的cola
值
预期结果:
cola CountOfDates colb
-----------------------------------------------------------------
111 2 2014-03-02,2014-03-03
121 4 2014-04-01,2014-04-02,2014-04-03,2014-04-04
131 1 2014-05-01
结果解释:上述结果显示,cola
在3个日期中输入,但不同的是2。与此类似,其他值也出现了 使用Xml Path()
技巧和colb
的Distinct Count
进行此操作
SELECT cola,
Count(distinct colb) Countofdates,
Stuff((SELECT Distinct ',' + CONVERT(VARCHAR(15), colb )
FROM #test t
WHERE t.cola = a.cola
FOR XML PATH ('')), 1, 1, '') colb
FROM #test a
GROUP BY cola
结果
cola Countofdates colb
---- ------------ -------------------------------------------
111 2 2014-03-02,2014-03-03
121 4 2014-04-01,2014-04-02,2014-04-03,2014-04-04
131 1 2014-05-01
试试这个(不使用XML-ClearSetBase方法和递归CTE的版本)
结果
cola colb count
-------------------------------------------------------------
111 2014-03-02,2014-03-03 2
121 2014-04-01,2014-04-02,2014-04-03,2014-04-04 4
131 2014-05-01 1
看起来他需要
Distinct colb
行和Distinct count
@Andrey,非常感谢。看起来你需要DistinctCountofdates
:)@Andrey-我已经在计算Distinctcolb
。尝试执行查询:)那么您忘了在answer@NoDisplayName,非常感谢。