在 teradata 中将行转换为 SQL 中的列
Convert rows to columns in SQL in teradata
我有这样的数据:
Name
Date
Bal
John
2022-01-01
10
John
2022-01-02
4
John
2022-01-03
7
David
2022-01-01
13
David
2022-01-02
15
David
2022-01-03
20
我想在 date
列下填充 Bal
列,例如:
Name
2022-01-01
2022-01-02
2022-01-03
John
10
4
7
David
13
15
20
我试过的是
SELECT
NAME,
CASE WHEN DATE= '2022-01-01' THEN EOD_BALANCE ELSE NULL END "01-Jan-22",
CASE WHEN DATE= '2022-01-02' THEN EOD_BALANCE ELSE NULL END "02-Jan-22"
FROM TABL1
但我没有得到所需的结果。以下是第一个答案中的查询结果:
你想在这里进行数据透视查询,这意味着你应该按名称聚合,然后取 CASE
表达式的最大值:
SELECT
NAME,
MAX(CASE WHEN DATE = '2022-01-01' THEN EOD_BALANCE END) AS "01-Jan-22",
MAX(CASE WHEN DATE = '2022-01-02' THEN EOD_BALANCE END) AS "02-Jan-22",
MAX(CASE WHEN DATE = '2022-01-03' THEN EOD_BALANCE END) AS "03-Jan-22"
FROM TABL1
GROUP BY NAME;
我有这样的数据:
Name | Date | Bal |
---|---|---|
John | 2022-01-01 | 10 |
John | 2022-01-02 | 4 |
John | 2022-01-03 | 7 |
David | 2022-01-01 | 13 |
David | 2022-01-02 | 15 |
David | 2022-01-03 | 20 |
我想在 date
列下填充 Bal
列,例如:
Name | 2022-01-01 | 2022-01-02 | 2022-01-03 |
---|---|---|---|
John | 10 | 4 | 7 |
David | 13 | 15 | 20 |
我试过的是
SELECT
NAME,
CASE WHEN DATE= '2022-01-01' THEN EOD_BALANCE ELSE NULL END "01-Jan-22",
CASE WHEN DATE= '2022-01-02' THEN EOD_BALANCE ELSE NULL END "02-Jan-22"
FROM TABL1
但我没有得到所需的结果。以下是第一个答案中的查询结果:
你想在这里进行数据透视查询,这意味着你应该按名称聚合,然后取 CASE
表达式的最大值:
SELECT
NAME,
MAX(CASE WHEN DATE = '2022-01-01' THEN EOD_BALANCE END) AS "01-Jan-22",
MAX(CASE WHEN DATE = '2022-01-02' THEN EOD_BALANCE END) AS "02-Jan-22",
MAX(CASE WHEN DATE = '2022-01-03' THEN EOD_BALANCE END) AS "03-Jan-22"
FROM TABL1
GROUP BY NAME;