We help IT Professionals succeed at work.
Get Started

GROUP BY from two tables

151 Views
Last Modified: 2015-04-22
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:
This problem has been solved!
Unlock 1 Answer and 4 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE