gpt4 book ai didi

sql - 按日期名称转换列中的行

转载 作者:行者123 更新时间:2023-12-03 14:15:02 24 4
gpt4 key购买 nike

我有这张 table

|ID | day_name   |        day_date     |
1 Monday 2018-01-08 00:00:00.000
2 Monday 2018-01-15 00:00:00.000
3 Monday 2018-01-22 00:00:00.000
4 Monday 2018-01-29 00:00:00.000
10 Tuesday 2018-01-16 00:00:00.000
11 Tuesday 2018-01-23 00:00:00.000
12 Tuesday 2018-01-30 00:00:00.000

我想将行旋转到列,所以结果集是这样的:
|        Monday            |       Tuesday           |
2018-01-08 00:00:00.000 2018-01-16 00:00:00.000
2018-01-15 00:00:00.000 2018-01-23 00:00:00.000
2018-01-22 00:00:00.000 2018-01-30 00:00:00.000
2018-01-29 00:00:00.000

我尝试了一些东西,但结果并不如预期:
WITH dayz AS
(
SELECT day_name, day_date,
[rn] = RANK() OVER (PARTITION BY day_name ORDER BY day_date)
FROM ISP_Cloud_DaysFromSession
)
SELECT
day_name,
MondayDates = MAX(CASE WHEN rn = 1 THEN day_date ELSE NULL END),
TuesdayyDates = MAX(CASE WHEN rn = 2 THEN day_date ELSE NULL END),
Column3 = MAX(CASE WHEN rn = 3 THEN day_date ELSE NULL END),
Column4 = MAX(CASE WHEN rn = 4 THEN day_date ELSE NULL END),
Column5 = MAX(CASE WHEN rn = 5 THEN day_date ELSE NULL END),
Column6 = MAX(CASE WHEN rn = 6 THEN day_date ELSE NULL END),
Column7 = MAX(CASE WHEN rn = 7 THEN day_date ELSE NULL END),
Column8 = MAX(CASE WHEN rn = 8 THEN day_date ELSE NULL END),
Column9 = MAX(CASE WHEN rn = 9 THEN day_date ELSE NULL END)
FROM
dayz
GROUP BY day_name

任何想法如何改变这个?

最佳答案

你离得不远,但你按错误的东西分组。行号是您想要的每一行,但您已将其定义为列

WITH Days AS
(SELECT day_name,
day_date,
RANK() OVER (PARTITION BY day_name ORDER BY day_date) AS [rn]
FROM dbo.ISP_Cloud_DaysFromSession)
SELECT MAX(CASE day_name WHEN 'Monday' THEN day_date END) AS Monday,
MAX(CASE day_name WHEN 'Tuesday' THEN day_date END) AS Tuesday
FROM Days
GROUP BY rn
ORDER BY rn ASC;

关于sql - 按日期名称转换列中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61887937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com