我需要在列中分开项目以在同一行中显示,但很难提出查询以完成此操作
例如,这是表当前显示的方式:
Person_id | Person_name | -test_date |
---|---|---|
000001 | Person1 | 11/12/2024 |
000001 | Person1 | 12/18/2024 |
000001 | Person1 | 01/12/2025 |
000002 | Person2 | 10/01/2024 |
000002 | Person2 | 11/01/2024 |
000002 | Person2 | 12/01/2024 |
000002 | Person2 | 01/01/2025 |
应该想形成以下类似的东西:
Person_id | Person_name | -test_date1 | -test_date2 | -test_date3 | -test_date4 |
---|---|---|---|---|---|
000001 | Person1 | 11/12/2024 | 12/18/2024 | 01/12/2025 | |
000001 | Person2 | 10/01/2024 | 11/01/2024 | 12/01/2024 | 01/01/2025 |
谢谢你!
我们可以在
ROW_NUMBER()
:的帮助下使用枢纽逻辑来处理此问题
WITH cte AS (
SELECT t.*, ROW_NUMBER() OVER (PARTITION BY person_id ORDED BY test_date) rn
FROM yourTable t
)
SELECT
person_id,
person_name,
MAX(CASE WHEN rn = 1 THEN test_date END) AS test_date1,
MAX(CASE WHEN rn = 2 THEN test_date END) AS test_date2,
MAX(CASE WHEN rn = 3 THEN test_date END) AS test_date3,
MAX(CASE WHEN rn = 4 THEN test_date END) AS test_date4
FROM cte
GROUP BY
person_id,
person_name;