使用奇怪的布局表进行透视

时间:2015-04-16 10:21:07

标签: sql tsql pivot

这是表的布局,请注意qA和qB两列上没有出现的类型a和c

type1   qA  type2  qB
x       10   z    11
y       5    x     3
z       4    c     3
y       3    y     1
z       8    z     5
x       5    x     9
a       3    x     2

要求的是根据qA和qB列的类型总和:

typ sum(qA) sum(qB) sum(qA)-sum(qB)
x      15      14        1
y       8       4        4
z      12      16       -4
c       0       3       -3
a       3       0        3

我可以通过以下查询使用union all来完成此操作:

SELECT *,qA-qB FROM
(
SELECT typ,sum(qA) qA,SUM(qB) qB
FROM
(
 SELECT type1 typ,SUM(qA) qA,0 qB
 FROM table1 
 GROUP BY type1

 UNION ALL

 SELECT type2 typ,0 qA,SUM(qB) qB
 FROM table1 
 GROUP BY type2    
 ) AS BA GROUP BY typ

) 
 AS T WHERE qA+qB>0
ORDER BY typ

但是我想知道在t-sql中是否有更好的解决方案来解决这个问题。

1 个答案:

答案 0 :(得分:0)

执行此操作的一种自然方式是从包含所有类型的表开始。然后:

select t.type, coalesce(a.qa, 0) as qa, coalesce(b.qb, 0) as qb, 
       ( coalesce(a.qa, 0)- coalesce(b.qb, 0) ) as diff
from alltypes t left join
     (select type1, sum(qa) as qa
      from table1
      group by type1
     ) a
     on t.type = a.type1 left join
     (select type2, sum(qb) as qb
      from table1
      group by type2
     ) b
     on t.type = b.type2;

您可以使用full outer join

获得相同的效果
select coalesce(a.type1, b.type2) as type,
       coalesce(a.qa, 0) as qa, coalesce(b.qb, 0) as qb, 
       ( coalesce(a.qa, 0)- coalesce(b.qb, 0) ) as diff
from (select type1, sum(qa) as qa
      from table1
      group by type1
     ) a
     on t.type = a.type1 full outer join
     (select type2, sum(qb) as qb
      from table1
      group by type2
     ) b
     on a.type1 = b.type2;

使用union all的解决方案也是一个非常合理的解决方案。