fmsol
asked on
GROUP BY from two tables
I have a table "hours" with some date-stamped records, and want sums from each day
Running this I get:
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:
I then get:
How can I GROUP/SUM the result BY the date?
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)
Running this I get:
DateField SumField
2015-04-11 90
2015-04-14 123
2015-04-15 30
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
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
How can I GROUP/SUM the result BY the date?
ASKER
Not sure if I understand this.
What about the hours table which needs to be UNIONed?
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)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Used a calendar table (which is a really smart idea in many situations)
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