总结多列

时间:2017-10-04 00:52:40

标签: sql

嗨,我有一张这样的桌子

Year Column1 column2 column3
 2015     A               B             C
 2015     D               A             B
 2016     F               C              A

我需要能够在列中总结某个子集显示的次数。我希望摘要表看起来像这个

Year Letter count
2015  A        2
2016  A        1
2015  B        2

如果有人能帮助我,我真的很感激!

1 个答案:

答案 0 :(得分:1)

您可以使用union all将数据分开,然后group by将其重新组合在一起:

select year, letter, count(*) 
from ((select year, column1 as letter from t) union all
      (select year, column2 as letter from t) union all
      (select year, column3 as letter from t) 
     ) yc
group by year, letter;

对于一组特定字母,请添加where letter in ('A', 'B')子句。