使用pivot将行转换为列

wooyq4lh  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(233)

我在sql server中有一个名为amountlist的表:

其中主键为“uniquecol1,uniquecol2,amountid”
根据amountd,我想将结果作为:

我面临使用pivot的挑战,因为只能使用聚合函数,但我需要字段的实际值。
更新:添加了我对使用联接的解决方案的尝试,但需要一些性能更高的查询。

xvw2m8pv

xvw2m8pv1#

你可以用 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
q3qa4bjr

q3qa4bjr2#

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

相关问题