Sunday, February 12, 2012

Converting Rows to Columns in SQL7

I do a:
SELECT * FROM xxx

And Get:
Date Place Sum
A M 1
A O 3
A P 2
B O 5
B M 4
B P 2

And I want it to look like:

Date M O P
A 1 3 2
B 4 5 2

Can you think of an EASY way to do this?
I can do it with a cursor that constructs a SQL statement, which I EXEC, but the 8000 character limit may prove to be a limiting factor.
sp_execsql is somewhat messy for the nature of this issue.
Any input is appreciated.

Thanks in advance."Brad Joss" <bradjoss@.hotmail.com> wrote in message news:<bgq7p7$m03$1@.news01.intel.com>...
> I do a:
> SELECT * FROM xxx
> And Get:
> Date Place Sum
> A M 1
> A O 3
> A P 2
> B O 5
> B M 4
> B P 2
> And I want it to look like:
> Date M O P
> A 1 3 2
> B 4 5 2
> Can you think of an EASY way to do this?
> I can do it with a cursor that constructs a SQL statement, which I EXEC,
> but the 8000 character limit may prove to be a limiting factor.
> sp execsql is somewhat messy for the nature of this issue.
> Any input is appreciated.
> Thanks in advance.
> --

Assuming that (Date, Place) is a unique combination, then this should work:

select
Date,
sum(case when Place = 'M' then Sum else NULL end) as 'M',
sum(case when Place = 'O' then Sum else NULL end) as 'O',
sum(case when Place = 'P' then Sum else NULL end) as 'P'
from
xxx
group by
Date

Simon|||i tried something but couldnt do anything about it. only if you send
me the solution you have it will help me(though with the limiting
factor)

Else i think at any point of time the 8000 character limit will be a
factor that will not allow you to do this always......
RVG

"Brad Joss" <bradjoss@.hotmail.com> wrote in message news:<bgq7p7$m03$1@.news01.intel.com>...
> I do a:
> SELECT * FROM xxx
> And Get:
> Date Place Sum
> A M 1
> A O 3
> A P 2
> B O 5
> B M 4
> B P 2
> And I want it to look like:
> Date M O P
> A 1 3 2
> B 4 5 2
> Can you think of an EASY way to do this?
> I can do it with a cursor that constructs a SQL statement, which I EXEC,
> but the 8000 character limit may prove to be a limiting factor.
> sp execsql is somewhat messy for the nature of this issue.
> Any input is appreciated.
> Thanks in advance.
> --

No comments:

Post a Comment