问题描述
我有一个 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