May 24, 2011 at 7:30 am
Hi folks,
I need to create a view and add the column (Hours) from Table A & Table B together to make the total sum figure. Any help appreciated.
Table A
Name | Hours
John | 20
John | 0
John | 10
Peter | 30
Peter | 0
Peter | 15
Table B
Name | Hours
John | 10
John | 0
John | 5
Peter | 10
Peter | 0
Peter | 5
I need to add the two columns from Table A & Table B togther so result would be
Name | Hours
John | 45
Peter | 60
May 24, 2011 at 7:38 am
This is a simple JOIN and SUM query. Please will you show us what you've tried so far?
John
May 24, 2011 at 7:57 am
Hi John,
Here is what i've tried so far. I've been googling all day but not getting anywhere
SELECT CAST(SUM(TB1.TimeDuration + TB2.TimeDuration) AS int) AS Total
FROM TB1 CROSS JOIN
TB2
May 24, 2011 at 8:00 am
Almost... you need an INNER JOIN on the Name column.
John
May 24, 2011 at 8:00 am
bpmosullivan (5/24/2011)
Hi John,Here is what i've tried so far. I've been googling all day but not getting anywhere
SELECT CAST(SUM(TB1.TimeDuration + TB2.TimeDuration) AS int) AS Total
FROM TB1 CROSS JOIN
TB2
SELECT Person, SUM(TimeDuration) AS TimeDuration FROM (
SELECT Person, TimeDuration FROM dbo.Table1
UNION ALL
SELECT Person, TimeDuration FROM dbo.Table2
) dtTimes
GROUP BY Person
May 24, 2011 at 8:01 am
John Mitchell-245523 (5/24/2011)
Almost... you need an INNER JOIN on the Name column.John
Actually you'd need a full outer because you need all data in both tables. So I preffer to user union all instead!
May 24, 2011 at 8:05 am
Ah yes - you're right. If you can't be sure that all names appear in both tables then an inner join won't work.
John
May 24, 2011 at 9:40 am
Thanks guys, that works great.
May 24, 2011 at 9:44 am
P.S. What's dtTimes (Alias / Derived table) ?
May 24, 2011 at 9:53 am
bpmosullivan (5/24/2011)
P.S. What's dtTimes (Alias / Derived table) ?
Yes, you can't use a derived table unless you name it.
Also from previous test those types of queries perform a little better if you do the group by only at the end instead of group by in both queries and then a 3rd time. That's why I did it like that.
May 24, 2011 at 10:08 am
Many thanks. Much appreciated
Viewing 11 posts - 1 through 10 (of 10 total)
You must be logged in to reply to this topic. Login to reply