I have the following data structure (simplified) declare @log table ( date smalldatetime, category char(3), value1 int, value2 int)insert into @log(date, category, value1, value2)select '2008-01-01', 'ABC', 11,12 union allselect '2008-01-02', 'ABC', 35,53 union allselect '2008-01-03', 'ABC', 38,62 union allselect '2008-01-05', 'ABC', 59,95 union allselect '2008-01-02', 'XYZ', 42,21 union allselect '2008-01-04', 'XYZ', 9,7 union allselect '2008-01-05', 'XYZ', 89,45 union allselect '2008-01-01', 'HHH', 70,52 union allselect '2008-01-03', 'HHH', 3,83 union allselect '2008-01-05', 'HHH', 26,77
where 1) date is always up to the day (no time variation)2) date and category can be considered a composite unique key Given a date range (let's say, from 2008-01-01 to 2008-01-05) I need to get the below:date abc_value1 abc_value2 xyz_value1 xyz_value2 hhh_value1 hhh_value2---------- ----------- ----------- ----------- ----------- ----------- -----------01/01/2008 11 12 NULL NULL 70 5201/02/2008 35 53 42 21 NULL NULL01/03/2008 38 62 NULL NULL 3 8301/04/2008 NULL NULL 9 7 NULL NULL01/05/2008 59 95 89 45 26 77
Ideally, the results include- every day in the date range (even if there is no corresponding data for that date)- the columns values to be dependent on the categories found within the date rangeI came up with this -- to fulfill requirement "every day in the date range"declare @dt table (d smalldatetime)insert into @dtselect '2008-01-01' union allselect '2008-01-02' union allselect '2008-01-03' union allselect '2008-01-04' union allselect '2008-01-05' -- to fulfill display all the categories (manually determined) select convert(varchar(10),d,101) as date, abc.value1 as abc_value1, abc.value2 as abc_value2, xyz.value1 as xyz_value1, xyz.value2 as xyz_value2, hhh.value1 as hhh_value1, hhh.value2 as hhh_value2from @dt dt left join @log abc on dt.d = abc.date and abc.category = 'ABC' left join @log xyz on dt.d = xyz.date and xyz.category = 'XYZ' left join @log hhh on dt.d = hhh.date and hhh.category = 'HHH'
just for the purpose of generating the end result example, but in a real life situation, both the date range and the categories that may fall within that date range... are dynamic. To make my head spin even more, I also suspect the issue of value2 AND value3 being pulled is making this one complicated statement.Any ideas? Thoughts? Suggestions? 