【问题标题】:Combine multiple rows into one row with same number of columns将多行合并为具有相同列数的一行
【发布时间】:2014-08-01 00:06:05
【问题描述】:

我的结果包含多行特定位置的优先级计数。我想简单地将这些结果变成一行以显示相同的信息。

我当前的代码是:

SELECT t.city_nm as CITY
              ,sum(case when h.priority = 1  then 1 else 0 end)as Priority1
              ,sum(case when h.priority = 2  then 1 else 0 end)as Priority2
              ,sum(case when h.priority = 3  then 1 else 0 end)as Priority3
from SHIPMENT h
INNER JOIN PET_EVT_LOG e 
on h.svc_id = e.svc_id
INNER JOIN LOCATION t
ON t.city_id = e.term_id
INNER JOIN CUSTOMER u
ON h.ship_cust = u.cust_id 
where u.cust_nm = 'CAL NATURAL'
            and e.evt_cd = 'ARRIVAL'
            and e.evt_dt_tm > date(current timestamp) - 7 day
GROUP BY t.city_nm, h.priority;

我的结果如下所示:

CITY      Priority1  Priority 2  Priority3
Atlanta      7           0          0
Atlanta      0           25         0
Atlanta      0           0          3
Baltimore    3           0          0
Baltimore    0           12         0
Baltimore    0           0          1
Detroit      9           0          0
Detroit      0           32         0
Detroit      0           0          5

如果一行中有一个数字计数,其他两个字段始终为 0,因此它们应该很容易组合以产生如下所示的结果:

CITY      Priority1  Priority 2  Priority3
Atlanta      7           25         3
Baltimore    3           12         1
Detroit      9           32         5

【问题讨论】:

    标签: database sum rows


    【解决方案1】:

    尝试替换

    GROUP BY t.city_nm, h.priority;
    

    通过

    GROUP BY t.city_nm;
    

    【讨论】:

    • 哇,我不知道我是怎么错过的。非常感谢。效果很好。
    猜你喜欢
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 2016-01-07
    • 2017-10-19
    • 2018-08-14
    • 1970-01-01
    相关资源
    最近更新 更多