如何解决将多行卷成具有相同列数和不同值的单行
我有一个 ID 列,其中包含针对特定属性的不同值。 我希望将 4 行转换为 1 行。有多条记录
UNIQID | NAME | AGE | SOURCE
123 | John | 25 | StoreA
928 | John | 25 | StoreB
456 | John | 25 | StoreC
528 | John | 25 | StoreD
我需要如下输出 -
UNIQID_A | UNIQID_B | UNIQID_C | UNIQID_D | NAME | AGE
123 | 928 | 456 | 528 | John | 25
我设法通过使用 sql 查询达到以下结果,但我不确定如何将这些值汇总为 1
SELECT CASE WHEN Source = 'StoreA' THEN UNIQID END AS UNIQID_A,CASE WHEN Source = 'StoreB' THEN UNIQID END AS UNIQID_B,CASE WHEN Source = 'StoreC' THEN UNIQID END AS UNIQID_C,CASE WHEN Source = 'StoreD' THEN UNIQID END AS UNIQID_D,ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY AGE) AS ROWNO,*
FROM Table
UNIQID_A | UNIQID_B | UNIQID_C | UNIQID_D | NAME | AGE | ROWNO
123 | NULL | NULL | NULL | John | 25 | 1
NULL | 928 | NULL | NULL | John | 25 | 2
NULL | NULL | 456 | NULL | John | 25 | 3
NULL | NULL | NULL | 528 | John | 25 | 4
感谢您的帮助。
解决方法
您可以在条件语句中使用 ^\d+[^-]+-\s+(?P<person>[^:]+):\s+(?P<text>.+)
聚合为一行,并按剩余的列分组
max
,
SELECT SUM(UNIQID_A) UNIQID_A,SUM(UNIQID_B) UNIQID_B,SUM(UNIQID_C) UNIQID_C,SUM(UNIQID_D) UNIQID_D,NAME,AGE FROM (
SELECT CASE WHEN Source = 'StoreA' THEN UNIQID END AS UNIQID_A,CASE WHEN Source = 'StoreB' THEN UNIQID END AS UNIQID_B,CASE WHEN Source = 'StoreC' THEN UNIQID END AS UNIQID_C,CASE WHEN Source = 'StoreD' THEN UNIQID END AS UNIQID_D,AGE
FROM Table) AS A
GROUP BY NAME,AGE
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。