使用SQL Server 2008 R2进行数据透视表查询

时间:2015-05-14 09:56:12

标签: sql sql-server sql-server-2008-r2 pivot

我的下表有两个字段,如下所示:

我想将以下数据的数据透视表显示为垂直形式。

test_10

create table test_10
(
    col1 varchar(10),
    col2 varchar(10)
);

插入记录

insert into test_10 values('A','2015-01-01'),('A','2015-01-05'),('A','2015-01-10'),('A','2015-02-15'),
                            ('B','2015-01-01'),('B','2015-01-05'),('B','2015-01-10'),('B','2015-02-15'),
                            ('C','2015-02-02'),('C','2015-02-05'),('C','2015-02-08'),('C','2015-02-16');

预期结果

ColX    Jan    Feb
-------------------                     
A       3      1
B       3      1
C       0      4

我的尝试

SELECT ColX,SUM(Jan) as Jan,SUM(Feb) as after
from
    ( 
        SELECT col1 as ColX,col1,
        (CASE WHEN col2 BETWEEN convert(date,'01-01-2015',105) AND convert(date,'31-01-2015',105) THEN count(col1) ELSE 0 END) as Jan, 
        (CASE WHEN col2 BETWEEN convert(date,'01-02-2015',105) AND convert(date,'28-02-2015',105) THEN count(col1) ELSE 0 end) as Feb
        from test_10
        Group By col1,col2
    ) a
Pivot 
(
    COUNT(col1)
    FOR col1 in([A],[B],[C])
)as pvt
GROUP BY ColX;  

但是获得结果

ColX    Jan    Feb
-------------------
A       1       1
B       1       1
C       0       1   

2 个答案:

答案 0 :(得分:2)

无需转轴,尝试条件聚合:

SELECT col1,
       SUM(CASE
             WHEN col2 BETWEEN CONVERT(DATE, '01-01-2015', 105) AND CONVERT(DATE, '31-01-2015', 105) THEN 1
             ELSE 0
           END) AS Jan,
       SUM(CASE
             WHEN col2 BETWEEN CONVERT(DATE, '01-02-2015', 105) AND CONVERT(DATE, '28-02-2015', 105) THEN 1
             ELSE 0
           END) AS Feb
FROM   test_10
GROUP  BY col1 

答案 1 :(得分:1)

在这里你的回答:Pivot:

SELECT ColX,SUM(Jan) as Jan,SUM(Feb) as Feb
from
    ( 
        SELECT col1 as ColX,col1,
        sum(CASE WHEN col2 BETWEEN convert(date,'01-01-2015',105) AND convert(date,'31-01-2015',105) THEN 1 ELSE 0 END) as Jan, 
        sum(CASE WHEN col2 BETWEEN convert(date,'01-02-2015',105) AND convert(date,'28-02-2015',105) THEN 1 ELSE 0 end) as Feb
        from test_10
        Group By col1
    ) a
Pivot 
(
    COUNT(col1)
    FOR col1 in([A],[B],[C])
)as pvt
GROUP BY ColX;  

输出:

ColX   Jan  Feb
A       3   1
B       3   1
C       0   4