计算日期并在列中显示逗号分隔值

时间:2014-12-26 06:12:47

标签: 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');
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。并且想要计算存在的不同日期 针对特定colb发生了cola列。并希望将逗号分隔日期显示为特定的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 

结果说明:上述结果显示{3}在3个日期中输入,但不同的是2.就像其他值出现一样。

2 个答案:

答案 0 :(得分:2)

使用Xml Path() Distinct Count colbSELECT 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

<强>结果

{{1}}

答案 1 :(得分:1)

试试这个(不使用XML的版本 - 使用递归CTE清除基于集合的方法)

with [base] as
(
    select cola, cast(colb as nvarchar(max)) [colb], 1 [count] from test
    union all
    select b.cola, b.colb+ ',' + cast(t.colb as nvarchar(10)), [count]+1
    from [base] b
    join test t on t.cola = b.cola
        and b.colb not like '%' + cast(t.colb as nvarchar(10)) + '%'
)
, ranked as
(
    select cola
    , colb
    , [count]
    , row_number() over (partition by cola order by [count] desc) [rank] 
    from [base]
)
select cola, colb, [count] from ranked where [rank] = 1

结果

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