We help IT Professionals succeed at work.

GROUP BY from two tables

fmsol
fmsol asked
on
I have  a table "hours" with some date-stamped records, and want sums from each day

SELECT CAST(DateStamp AS DATE) as DateField, SUM(Lengde) as SumField
FROM hours
GROUP BY CAST(DateStamp AS DATE)
ORDER BY CAST(Dato AS DATE)

Open in new window


Running this I get:
DateField	SumField
2015-04-11	90
2015-04-14	123
2015-04-15	30

Open in new window


But since I want the sum of hours from last 14 days, including a 0 on days with no records I've tried to UNION then following:
DECLARE @dt DATE, @dtEnd DATE
set @dt = dateadd(day,-13,getdate())
set @dtEnd = dateadd(day, 14, @dt)
select dateadd(day, number, @dt) AS Dato, '0' AS SumField
from 
    (select distinct number from master.dbo.spt_values
     where name is null
    ) n
where dateadd(day, number, @dt) < @dtEnd

Open in new window


I then get:
DateField	SumField
2015-04-03	0
2015-04-04	0
2015-04-05	0
2015-04-06	0
2015-04-07	0
2015-04-08	0
2015-04-09	0
2015-04-10	0
2015-04-11	0
2015-04-11	90
2015-04-12	0
2015-04-13	0
2015-04-14	123
2015-04-14	0
2015-04-15	0
2015-04-15	30
2015-04-16	0

Open in new window


How can I GROUP/SUM the result BY the date?
Comment
Watch Question

Commented:
DECLARE @dt DATE, @dtEnd DATE
set @dt = dateadd(day,-13,getdate())
set @dtEnd = dateadd(day, 14, @dt)

SELECT Dato , SUM(SumField) AS SumField FROM
(
select dateadd(day, number, @dt) AS Dato, '0' AS SumField
from
    (select distinct number from master.dbo.spt_values
     where name is null
    ) n
where dateadd(day, number, @dt) < @dtEnd
) A Group by Dato

Author

Commented:
Not sure if I understand this.
What about the hours table which needs to be UNIONed?

SELECT CAST(DateStamp AS DATE) as DateField, SUM(Lengde) as SumField
FROM hours
GROUP BY CAST(DateStamp AS DATE)
ORDER BY CAST(Dato AS DATE)

Open in new window

Author

Commented:
Used a calendar table (which is a really smart idea in many situations)