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 2005 Forums
 Transact-SQL (2005)
 What's the more eficient method?

Author  Topic 

xabi
Starting Member

1 Post

Posted - 2008-04-17 : 05:43:27
Hello, I've a table "TblSales" with this structure: Year (integer), CustomerId (integer) and Sales (float).

SELECT Year, CustomerId, Sales FROM TblSales

Year;CustomerId;Sales
2000;1;100
2000;1;50
2000;2;200
2001;1;10
2001;2;20
etc...

I've 10 distinct CustomerId (from 1 to 10)

I want to make a row for every year with x columns (1 for every diferent CustomerId) with the sum of sales of this Customer on this year.

I've thounsdands rows. What's the more eficient method?

Thanks

spirit1
Cybernetic Yak Master

11752 Posts

Posted - 2008-04-17 : 05:45:54
search around here for "pivot" and "cross tab".

you'll get plenty of results

_______________________________________________
Causing trouble since 1980
blog: http://weblogs.sqlteam.com/mladenp
SSMS Add-in that does a few things: www.ssmstoolspack.com
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-04-17 : 05:47:21
[code]SELECT Year,
SUM(CASE WHEN Customer_ID=1 THEN Sales ELSE 0 END) AS Customer1,
SUM(CASE WHEN Customer_ID=2 THEN Sales ELSE 0 END) AS Customer2,
.....
SUM(CASE WHEN Customer_ID=10 THEN Sales ELSE 0 END) AS Customer10
FROM TblSales
GROUP BY Year[/code]
Go to Top of Page
   

- Advertisement -