SQL self join multiple times

后端 未结 3 1335
庸人自扰
庸人自扰 2021-01-24 05:44

I have a single database table that stores week entries.

Id        Value     WeekId
1         1.0000    1
2         2.0000    1

There can be up

3条回答
  •  攒了一身酷
    2021-01-24 06:17

    These entries are not returning because your WHERE clause explicitly filters them out when the joined tables return NULL values.

    This solution adds a sequential rownumber to each record, restarting to 1 for each week. This allows you to use this sequential number in a PIVOT statement

    SQL 2000 Statement

    SELECT  *
    FROM    (
              SELECT  (SELECT  COUNT(*) 
                       FROM    testWeekEntries 
                       WHERE   Id <= we.Id 
                               AND WeekId = we.WeekId) as rn
                      , Value
                      , WeekId
              FROM    testWeekEntries we
            ) q
    PIVOT   (MAX(Value) FOR rn IN ([1],[2],[3]) ) AS PVT
    

    SQL 2008 Statement

    ;WITH q AS (
    SELECT  rn = ROW_NUMBER() OVER (PARTITION BY WeekId ORDER BY Id)
            , Id
            , Value
            , WeekId
    FROM    [testWeekEntries] as w1 
    )
    SELECT  Value
            , (SELECT Value FROM q q1 WHERE q1.rn = q.rn + 1 AND q1.WeekId = q.WeekId)
            , (SELECT Value FROM q q2 WHERE q2.rn = q.rn + 2 AND q2.WeekId = q.WeekId)
    FROM    q
    WHERE   q.rn = 1
    

提交回复
热议问题