小编典典

SQL``转换''查询

sql

我在表上有这些数据(使用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

现在最困难的部分是:假设我没有其他数据字段指定哪个记录是早餐,午餐或晚餐。我想将它们与最短的开始时间相关联,即,开始时间越短将是早餐,其次就越是午餐,晚餐就越高(假设所有三个(并且只有三个)记录总是被填充)。

有任何想法吗?


阅读 158

收藏
2021-04-07

共1个答案

小编典典

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
2021-04-07