简体   繁体   English

如何将共享一个相同值的多行折叠成一行 PRESTO SQL

[英]How do I collapse multiple rows that shares one identical value into a single row PRESTO SQL

I have this table我有这张桌子

id ID cnt1 cnt1 cnt2 cnt2
7775 7775 1 1个
7775 7775 2 2个

I would like to combine the rows so that it comes out to this我想把这些行合并起来,这样就可以了

id ID cnt1 cnt1 cnt2 cnt2
7775 7775 1 1个 2 2个

I've tried a self join but it only appends the rows to the bottom.我试过自连接,但它只将行附加到底部。 Any ideas?有任何想法吗? thank you!谢谢你!

use SubQuery and join as follows使用SubQuery并按如下方式join

SELECT T1.Id,
       Cnt1,
       Cnt2
FROM   (SELECT Id,
               Cnt1
        FROM   Table
        WHERE  Cnt1 IS NOT NULL) T1
       JOIN (SELECT Id,
                    Cnt2
             FROM   Table
             WHERE  Cnt2 IS NOT NULL) T2
         ON T1.Id = T2.Id  

Depending on required logic you can use group by id with corresponding aggregate function, for example max (or sum ), which will ignore null values.根据所需的逻辑,您可以使用group by id和相应的聚合function,例如max (或sum ),这将忽略 null 值。

-- sample data
WITH dataset (id, cnt1, cnt2) AS (
    VALUES (7775, 1, null),
        (7775, null, 2)
) 

-- query
select id,
    max(cnt1) cnt1,
    max(cnt2) cnt2
from dataset
group by id

Output: Output:

id ID cnt1 cnt1 cnt2 cnt2
7775 7775 1 1个 2 2个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM