Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Combining data from two different years

Author  Topic 

esan
Starting Member

1 Post

Posted - 2010-08-11 : 10:03:59
I have the data in the table as follows.

Date Group Data
01/01/2009 A 2
02/01/2009 A 3
03/01/2009 B 4
04/01/2009 B 5

01/01/2010 A 1
02/01/2010 A 6
03/01/2010 B 7
04/01/2010 B 8

Now i am trying to build a query with the following output.

Group 2009 Total 2010 Total
A 5 7
B 9 15

I am able to get it for 1 year but not for 2 different years.Any help is greatley apprecitated.




vijayisonly
Master Smack Fu Yak Hacker

1836 Posts

Posted - 2010-08-11 : 10:33:28
[code]select [Group]
,SUM(case when datepart(yy,Date) = 2009 then [Data] else 0 end) as [2009_Total]
,SUM(case when datepart(yy,Date) = 2010 then [Data] else 0 end) as [2010_Total]
from YourTable
group by [Group][/code]
Go to Top of Page

vaibhavktiwari83
Aged Yak Warrior

843 Posts

Posted - 2010-08-11 : 10:37:49
[code]
SELECT [GROUP], SUM( Data2009 ) Total2009, SUM( Data2010 ) Total2010
FROM
(
SELECT [GROUP],
CASE WHEN Year(Date) = 2009 THEN data ELSE 0 END AS Data2009,
CASE WHEN Year(Date) = 2010 THEN data ELSE 0 END AS Data2010
FROM testTable
) A
GROUP BY [GROUP]
[/code]

Vaibhav T

To walk FAST walk ALONE
To walk FAR walk TOGETHER
Go to Top of Page

vaibhavktiwari83
Aged Yak Warrior

843 Posts

Posted - 2010-08-11 : 10:39:31
@vijayisonly - oops i dint see your reply.
yours is better one having same output.

Vaibhav T

To walk FAST walk ALONE
To walk FAR walk TOGETHER
Go to Top of Page

vijayisonly
Master Smack Fu Yak Hacker

1836 Posts

Posted - 2010-08-11 : 10:44:58
quote:
Originally posted by vaibhavktiwari83

@vijayisonly - oops i dint see your reply.
yours is better one having same output.

Vaibhav T

To walk FAST walk ALONE
To walk FAR walk TOGETHER


Np.
Both queries are same ...just different ways of writing it.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-08-13 : 11:19:34
For unknown number of years, use
http://beyondrelational.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -