Sql Server数据透视表不分组结果集

时间:2012-02-22 06:15:56

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

我的表格值如下 -

EMP_CODE | LEAVENAME | APP_TYPE |  LEAVE_DATE | ACT_DAYS
--------------------------------------------------------
ST006    |  CL       | P        | 2012-01-03  | 1.0
ST006    |  CL       | P        | 2012-01-18  | 1.0
ST006    |  SL       | P        | 2012-01-27  | 1.0
ST002    |  CL       | P        | 2012-01-04  | 1.0
ST002    |  CL       | P        | 2012-01-12  | 1.0
ST002    |  SL       | P        | 2012-01-27  | 1.0
OCO038   |  CL       | P        | 2012-01-27  | 1.0
HO188    |  CL       | P        | 2012-01-09  | 1.0
HO188    |  CL       | P        | 2012-01-30  | 1.0
HO085    |  CL       | P        | 2012-01-19  | 1.0
HO085    |  SL       | P        | 2012-01-23  | 1.0

我已将此查询编写为将所有请假类型汇总为每个员工的列。每位员工必须只有一行。

SELECT EMP_CODE,[CL],[LWP],[PL],[SL] FROM LEAVE_DETAIL L 
PIVOT (SUM(ACT_DAYS) FOR LEAVENAME IN ([CL],[LWP],[PL],[SL])) 
AS PVT ORDER BY EMP_CODE;

但是这个查询没有给我预期的输出。每个员工都有不止一行,这不是我想要的。

下表显示了预期的输出 -

EMP_CODE |  CL  | SL  |
---------|------|-----|
ST006    | 2.0  | 1.0 |
ST002    | 2.0  | 1.0 |
OCO038   | 1.0  | 0.0 |
HO188    | 2.0  | 0.0 |
HO085    | 1.0  | 1.0 |

请帮忙。

2 个答案:

答案 0 :(得分:9)

在查询中甚至不需要group by。因为枢轴的作用是它在其他列上“分组”。这个解决方案的关键是内部选择。我认为首先与小组合作并然后再申请一笔金额和小组并不是一个神圣的习惯。

SELECT 
    EMP_CODE,
    [CL],
    [LWP],
    [PL],
    [SL] 
FROM 
(
    SELECT 
        EMP_CODE, 
        LEAVENAME, 
        ACT_DAYS
    FROM 
        @tmp_emp
) L 
PIVOT
(
    SUM(ACT_DAYS) 
    FOR LEAVENAME IN ([CL],[LWP],[PL],[SL])
) 
AS PVT 
ORDER BY EMP_CODE

这会得到相同的结果。

答案 1 :(得分:2)

你可以尝试如下。你可以替换你的表,因为我测试的临时表与你的表一样。

create table #tmp_emp (EMP_CODE varchar(10),LEAVENAME char(2), APP_TYPE char(1),LEAVE_DATE datetime,ACT_DAYS decimal(2,1))

insert into #tmp_emp values ('ST006','CL','P ','2012-01-03','1.0');
insert into #tmp_emp values ('ST006','CL','P ','2012-01-18','1.0');
insert into #tmp_emp values ('ST006','SL','P ','2012-01-27','1.0');
insert into #tmp_emp values ('ST002','CL','P ','2012-01-04','1.0');
insert into #tmp_emp values ('ST002','CL','P ','2012-01-12','1.0');
insert into #tmp_emp values ('ST002','SL','P ','2012-01-27','1.0');
insert into #tmp_emp values ('OCO038','CL','P ','2012-01-27','1.0');
insert into #tmp_emp values ('HO188','CL','P ','2012-01-09','1.0');
insert into #tmp_emp values ('HO188','CL','P ','2012-01-30','1.0');
insert into #tmp_emp values ('HO085','CL','P ','2012-01-19','1.0');
insert into #tmp_emp values ('HO085','SL','P ','2012-01-23','1.0');

SELECT EMP_CODE,[CL],[LWP],[PL],[SL] 
FROM 
(
    select EMP_CODE, LEAVENAME, sum(ACT_DAYS) ACT_DAYS
    from #tmp_emp
    group by EMP_CODE, LEAVENAME
) L 
PIVOT (SUM(ACT_DAYS) FOR LEAVENAME IN ([CL],[LWP],[PL],[SL])) 
AS PVT ORDER BY EMP_CODE;