• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 127
  • Last Modified:

GROUP BY from two tables

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?
0
fmsol
Asked:
fmsol
  • 3
1 Solution
 
sarabhaiCommented:
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
0
 
fmsolAuthor 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

0
 
fmsolAuthor Commented:
0
 
fmsolAuthor Commented:
Used a calendar table (which is a really smart idea in many situations)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now