tags:

views:

44

answers:

1

Is there any simple SQL query to convert this below data

Date - Item - cost
10/31/2009 - a - 1
10/31/2009 - b - 2
10/31/2009 - c - 3
10/31/2009 - d - 4

11/30/2009 - a - 5
11/30/2009 - b - 6
11/30/2009 - c - 7
11/30/2009 - d - 8

Into below report format without any application logic/store procedure/reporting tool?

Item - 10/31/2009 - 11/30/2009
a - 1 - 5
b - 2 - 6
c - 3 - 7
d - 4 - 8

Sorry, couldn't come up with a better title..

A: 
SELECT
  item,
  MAX(CASE WHEN dt = CAST('2009-10-31' AS DATE) THEN cost END) AS oct2009_cost,
  MAX(CASE WHEN dt = CAST('2009-11-30' AS DATE) THEN cost END) AS nov2009_cost,
  MAX(CASE WHEN dt = CAST('2009-12-31' AS DATE) THEN cost END) AS dec2009_cost
FROM items
GROUP BY
  item;
lins314159
The date's are not static. I can't hard-code dates. The dates should come the table itself. Any other ideas? Appreciate you help.
Broken Link
Do you always know how many dates you will need? If not, you will need to generate the query dynamically. What criteria do you apply to find out such dates (eg. the 5 latest end of month dates for which tehre is data)?
lins314159
I'm trying to SQL pivot and do this, not there yet. But almost there. http://msdn.microsoft.com/en-us/library/ms177410.aspx
Broken Link