sql >> Base de Datos >  >> RDS >> Sqlserver

Consulta de transformación SQL

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