通过旋转将行转换为列

时间:2016-11-10 21:31:57

标签: sql sql-server tsql pivot

我正在学习SQL,我想创建一个查询,创建由表中的值组成的新列。我有一个名为transactions的列,同一家公司有多个交易。表看起来像这样:

Id  Name   Payd
1   John   5.00
2   Adam   5.00
3   John   10.00
4   John   10.00
5   Adam   15.00

我想做这样的事情:

Id  Name   5.00 10.00 15.00 Sum
1   John   5.00 20.00 0     25.00
2   Adam   5.00 0     15.00 20.00

我正在考虑使用PIVOT功能,但我在执行方面遇到了麻烦。我的代码看起来像这样:

(select emplployer, CAST (4.00 as decimal(10,0)) as [4.00],
CAST (5.00 as decimal(10,0)) as [5.00],
CAST (10.00 as decimal(10,0)) as [10.00],
CAST (18.00 as decimal(10,0)) as [18.00],
CAST (20.00 as decimal(10,0)) as [20.00]
from (select Name, cast(Payd as decimal(10,0)) as summ from employee) q1
pivot
(
    sum(summ) for employer in ([4.00], [5.00], [10.00], [18.00], [20.00])
)pvt;

1 个答案:

答案 0 :(得分:3)

条件聚合方法:

SELECT
    Name
    ,SUM(CASE WHEN Payd = 5 THEN Payd ELSE 0 END) as [5.00]
    ,SUM(CASE WHEN Payd = 10 THEN Payd ELSE 0 END) as [10.00]
    ,SUM(CASE WHEN Payd = 15 THEN Payd ELSE 0 END) as [15.00]
    ,SUM(Payd) as [Sum]
FROM
    @Employees
GROUP BY
    Name

使用Pivot的一种方法:

;WITH cte AS (
    SELECT
       Name
       ,Payd
       ,Payd as PaydColNames
    FROM
       @Employees
)

SELECT
    Name
    ,[5.00] = ISNULL([5.00],0)
    ,[10.00] = ISNULL([10.00],0)
    ,[15.00] = ISNULL([15.00],0)
    ,[Sum] = ISNULL([5.00],0) + ISNULL([10.00],0) + ISNULL([15.00],0)
FROM
    cte
    PIVOT (
       SUM(Payd) FOR PaydColNames IN ([5.00],[10.00],[15.00])
    ) p

您似乎遇到的问题是您尝试使用相同的列来旋转聚合,而这不会为您提供所需的结果。因此,您必须复制Payd列,以便将数据用作PIVOT和Aggregate。然后因为当值为NULL时你想要0,你必须使用ISNULL或COALESCE来消除NULL。在我看来,条件聚合将更好地为您提供这样的用途。

测试数据

DECLARE @Employees AS TABLE (Id INT, Name VARCHAR(50), Payd MONEY)
INSERT INTO @Employees VALUES
(1,'John',5.00)
,(2,'Adam',5.00)
,(3,'John',10.00)
,(4,'John',10.00)
,(5,'Adam',15.00)