Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 fill missing days and grouped by totals

Author  Topic 

lappin
Posting Yak Master

182 Posts

Posted - 2012-02-07 : 11:12:36
I have a function which returns grouped totals by day and group.
e.g
Day Group Total
Mon a 123
Mon b 55
Mon e 45
Tue b 33
Tue c 99

I need to fill missing for each day Mon to Friday and groups a to e.
So the above should look like this:
Day Group Total
Mon a 123
Mon b 55
Mon c 0
Mon d 0
Mon e 45
Tue a 33
Tue b 33
Tue c 99
Tue d 0
Tue e 0

I've looked at CTE recursion but any examples I found do not have grouping. I also have a filler table with Mon to Fri and groups a to e for each day.

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-02-07 : 12:00:50
You can cross join your filler tables to get all combinations of days and groups, and then do a left join to that. Or you could generate the filler tables on the fly and then do the cross join, for example this:
;WITH Days([Day]) AS
( SELECT 'Mon' UNION ALL SELECT 'Tue'),

Groups([Group]) AS
( SELECT 'a' UNION ALL SELECT 'b' UNION ALL SELECT 'c' UNION ALL SELECT 'd' UNION ALL SELECT 'e')

SELECT
d.*,
g.*
--, other columns here
FROM
(Days d
CROSS JOIN Groups g)
LEFT JOIN YourOtherTables y ON ....
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-02-07 : 12:47:09
quote:
Originally posted by lappin

I have a function which returns grouped totals by day and group.
e.g
Day Group Total
Mon a 123
Mon b 55
Mon e 45
Tue b 33
Tue c 99

I need to fill missing for each day Mon to Friday and groups a to e.
So the above should look like this:
Day Group Total
Mon a 123
Mon b 55
Mon c 0
Mon d 0
Mon e 45
Tue a 33
Tue b 33
Tue c 99
Tue d 0
Tue e 0

I've looked at CTE recursion but any examples I found do not have grouping. I also have a filler table with Mon to Fri and groups a to e for each day.



i hope this is typo and not intentional

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

lappin
Posting Yak Master

182 Posts

Posted - 2012-02-08 : 04:16:18
Sunita thanks for the help. Visakh I don't understand, am I missing something obvious?
Edit: Sorry see the typo now. Yes it should be
Tue a 0
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-02-08 : 14:14:13
Ok..Then fine with that

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -