gpt4 book ai didi

SQL "transform"查询

转载 作者:行者123 更新时间:2023-12-04 06:59:13 25 4
gpt4 key购买 nike

我在表上有这些数据(使用 SQL Server 2005):

ID    ParentID    StartTime    EndTime
77 62 08:00:00 11:00:00
78 62 12:00:00 15:00:00
79 62 18:00:00 22:00:00

我想把它改成这样:
ParentID  BreakfastStart  BreakfastEnd  LunchStart  LunchEnd  DinnerStart  DinnerEnd
62 08:00:00 11:00:00 12:00:00 15:00:00 18:00:00 22:00:00

现在困难的部分是:假设我没有其他数据字段指定哪个记录是早餐、午餐或晚餐。我想将它们与最低的开始时间联系起来,即,较低的开始时间是早餐,下一个较低的将是午餐,较高的将是晚餐(假设所有三个(并且只有三个)记录总是被填满)。

有任何想法吗?

最佳答案

WITH    q AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY parentID ORDER BY StartTime) AS rn
FROM mytable
)
SELECT qb.ParentID,
qb.StartTime AS BreakfastStart, qb.EndTime AS BreakfastEnd,
ql.StartTime AS LunchStart, ql.EndTime AS LunchEnd,
qd.StartTime AS DinnerStart, qd.EndTime AS DinnerEnd
FROM q qb
LEFT JOIN
q ql
ON ql.parentID = qb.parentID
AND ql.rn = 2
LEFT JOIN
q qd
ON qd.parentID = qb.parentID
AND qd.rn = 3
WHERE qb.rn = 1

关于SQL "transform"查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2140958/

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