SQL self join multiple times

后端 未结 3 1334
庸人自扰
庸人自扰 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:15

    You will need to add in your where clause the possibility that w2.Id is null or w3.id is null

    So something like

    WHERE 
      (w2.Id is null and w3.id is null) or 
      (w3.id is null and w1.id < w2.id) or 
      (w1.id < w2.id and w2.id < w3.id)
    
    0 讨论(0)
  • 2021-01-24 06:15

    You can also use PIVOT

    ;WITH CTE AS
    (
    SELECT Value,
           WeekId,
           ROW_NUMBER() OVER (PARTITION BY WeekId ORDER BY Id) AS RN
    FROM   [List].[dbo].[testWeekEntries]       
    )
    SELECT *
    FROM CTE 
    PIVOT (MAX(Value) FOR RN IN ([1],[2],[3]) ) AS PVT
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题