使用 PIVOT 将行转换为列

Convert rows to columns using PIVOT

我在 SQL 服务器中有一个名为 table 的 AmountList :

其中主键是“UniqueCol1、UniqueCol2、AmountID”

并且在 AmountID 的基础上,我想将结果转换为:

我在使用 Pivot 时面临挑战,因为只能使用聚合函数,但我需要字段的实际值。

更新: 添加了我对使用 JOINS 的解决方案的尝试,但需要一些具有更高性能的查询。

您可以使用 case 表达式来实现您的预​​期输出。

select
  uniqueCol1,
  uniqueCol2,
  sum(case when AmountID = 1 then amount end) as Amount1MO,
  sum(case when AmountID = 3 then amount end) as Amount3MO,
  sum(case when AmountID = 6 then amount end) as Amount6MO,
  sum(case when AmountID = 9 then amount end) as Amount9MO,
  sum(case when AmountID = 12 then amount end) as Amount12MO
from AmountList
group by
  uniqueCol1,
  uniqueCol2
select 
CASE WHEN t1.uniqueCol1 is not null THEN t1.uniqueCol1
WHEN t2.uniqueCol1 is not null THEN t2.uniqueCol1
t3.uniqueCol1 is not null THEN t3.uniqueCol1
t4.uniqueCol1 is not null THEN t4.uniqueCol1
t5.uniqueCol1 is not null THEN t5.uniqueCol1
ELSE NULL END AS uniqueCol1,
CASE WHEN t1.uniqueCol2 is not null THEN t1.uniqueCol2
WHEN t2.uniqueCol2 is not null THEN t2.uniqueCol2
t3.uniqueCol2 is not null THEN t3.uniqueCol2
t4.uniqueCol2 is not null THEN t4.uniqueCol2
t5.uniqueCol2 is not null THEN t5.uniqueCol2
ELSE NULL END AS uniqueCol2,
Amount1MO,Amount3MO,Amount6MO,Amount9MO,Amount12MO from

    (
    select
      uniqueCol1,
      uniqueCol2,
      Amount as Amount1MO,
    from AmountList
    where AmountID = 1
    )t1

        FULL OUTER JOIN

    (
    select
      uniqueCol1,
      uniqueCol2,
      Amount as Amount3MO,
    from AmountList
    where AmountID = 3
    )t2

        ON t1.uniqueCol1=t2.uniqueCol1 AND t1.uniqueCol2 = t2.uniqueCol2
        FULL OUTER JOIN

    (
    select 
      uniqueCol1,
      uniqueCol2,
      Amount as Amount6MO,
    from AmountList
    where AmountID = 6
    )t3

        ON t2.uniqueCol1=t3.uniqueCol1 AND t2.uniqueCol2 = t3.uniqueCol2
        FULL OUTER JOIN

    (
    select
      uniqueCol1,
      uniqueCol2,
      Amount as Amount9MO,
    from AmountList
    where AmountID = 9
    )t4

        ON t3.uniqueCol1=t4.uniqueCol1 AND t3.uniqueCol2 = t4.uniqueCol2
        FULL OUTER JOIN

    (
    select
      uniqueCol1,
      uniqueCol2,
      Amount as Amount12MO,
    from AmountList
    where AmountID = 12
    )t5