如何汇总来自两列

时间:2015-08-31 21:43:42

标签: sql select count sum

我在表格中有以下信息

    Load Number  Origin  Destination
    1            AR      TX
    2            AR      AL
    3            TX      MS
    4            WA      AR

我需要有关SQL语句的帮助,该语句将产生以下结果

    State      Origin   Destination
    AR         2        1
    TX         1        1
    WA         1        
    MS                  1

我已经尝试过无数种类型的SELECT语句,其中包含各种类型的COUNTS和最后的GROUP BY,但我无法获得我正在寻找的结果。非常感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

怎么样:

select state,
       sum(origin) origin,
       sum(destination) destination
from   (select origin as state,
               0 as destination,
               1 as origin
        from   my_table
        union all
        select destination,
               1,
               0
        from   my_table)
group by state

答案 1 :(得分:2)

您可以先构建内部查询,从Origin和Destination列中选择所有不同的状态。然后,您可以将其连接回主表并进行条件聚合。

Demo

select x.state, 
sum(case when x.state = t.Origin then 1 end),
sum(case when x.state = t.Destination then 1 end)
from tablename t 
join (
select Origin as State
from tablename
union
select Destination
from tablename ) x
on t.Origin = x.state or t.Destination = x.state
group by x.state