I have the following query in SQL Server 2005 that fetches the result that is mentioned below it.
select Distinct(date),id,
sum(convert(float,Gross)),
count(*) as no from Daily
group by date,id
order by date desc
Date id Gross Count
2012-11-25 00:00:00.000 Client id1 1232.6140752 12
2012-11-25 00:00:00.000 Client id2 1183.75621528 88
2012-11-26 00:00:00.000 Client id3 4561.459086 67
2012-11-26 00:00:00.000 Client id4 6781.15660608 440
Now how do I get the result in the following format. This looks like a pivot query is reqd please help
id Date1 Date2 Date3 Date4 Date5 Date6 Date7
Client id1 Gross
Client id2 Gross
Client id3 Gross
There are two ways that you can
PIVOT, either a static version where you hard-code all of the date values or a dynamic version which will generate the list of dates at run-time.Static Version:
If you had a limited number of dates your query will be similar to this.
See SQL Fiddle with Demo
Dynamic Version:
This version generates dynamic SQL to get the list of dates at run-time. Your code will be similar to this:
See SQL Fiddle with Demo