选择sql查询行到列

时间:2018-04-19 07:50:57

标签: sql pivot

我有一个选择查询leavetype和nofdays

leavetype   nofdays

sl           2
cl           2
pl           4
sl           3
cl           5
pl           6

我需要在每行中使用noofday之和选择查询,并选择leavetype,cl,sl,pl 最终数据应采用以下表格形式:

Sl   Pl    Cl
5    10    7

2 个答案:

答案 0 :(得分:1)

执行conditional聚合

select empid,
       sum(case when leavetype = 'sl' then nofdays else 0 end) as sl,
       sum(case when leavetype = 'pl' then nofdays else 0 end) as pl,
       sum(case when leavetype = 'cl' then nofdays else 0 end) as cl
from table t
group by empid; 

答案 1 :(得分:0)

我是使用SQL Server完成此操作,不确定您使用的DBMS,但逻辑类似

建立表格:

DECLARE @table TABLE (col1 varchar(2), col2 int)
INSERT INTO @table VALUES
('sl',2),
('cl',2),
('pl',4),
('sl',3),
('cl',5),
('pl',6)

透视声明:

SELECT *
FROM
(
    SELECT col1,
           col2
    FROM @table
) p PIVOT(SUM(col2) FOR col1 IN([sl],
                                [cl],
                                [pl])) AS pvt;

返回:

sl  cl  pl
5   7   10

MS Docs就在这里: https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx