【问题标题】:How to SUM values from two columns如何对两列中的值求和
【发布时间】:2015-11-26 00:43:26
【问题描述】:

我在表格中有以下信息

    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,但我无法得到我正在寻找的结果。非常感谢任何帮助。

【问题讨论】:

    标签: sql select count sum


    【解决方案1】:

    怎么样:

    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
    

    【讨论】:

    • 我绝对认为这是更好的方法。
    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2020-08-19
      • 2021-01-26
      • 2023-03-25
      • 2020-02-11
      • 1970-01-01
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多