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 to three entries with the same week.
So I figured using a self join would solve this
SELECT w1.Value, w2.Value, w3.Value
FROM [List].[dbo].[testWeekEntries] as w1
LEFT OUTER JOIN [List].[dbo].[testWeekEntries] as w2 ON w1.WeekId = w2.weekId
LEFT OUTER JOIN [List].[dbo].[testWeekEntries] as w3 ON w2.WeekId = w3.WeekId
WHERE w1.Id < w2.Id AND w2.Id < w3.Id
The problem: It worls fine with the maximum number of entries however it doesn't pull back a row with one or two entries.
Is there a different type of join I can use to pull back a row with only one or two entries or a different way of approaching this?
You can also use
PIVOT
You will need to add in your where clause the possibility that
w2.Id is null
orw3.id is null
So something like
These entries are not returning because your
WHERE
clause explicitly filters them out when the joined tables returnNULL
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
SQL 2008 Statement