I have the following table structure and would like to pivot the data
below. The table was comprised of raw data grouped to find the count.
count question choice question2 choice2
-- -- -- --
--
7 are you happy no are you yes
14 are you happy yes are you yes
6 are you happy yes are you no
15 are you happy no are you no
When I Pivot
Select * from TableAbove
Pivot
(
Sum(count)
FOR Choice2 IN
('YES', 'NO')
)
I get
2 lines
Question choice yes no
-- -- -- --
are you happy yes 14 null
are you happy yes null 6
are you happy no 7 null
are you happy no null 15
Any Ideas would be appreciatedOn 30 May 2006 14:02:31 -0700, Troutbum wrote:
>I have the following table structure and would like to pivot the data
>below. The table was comprised of raw data grouped to find the count.
>count question choice question2 choice2
>-- -- -- --
> --
>7 are you happy no are you yes
>14 are you happy yes are you yes
>6 are you happy yes are you no
>15 are you happy no are you no
>When I Pivot
>Select * from TableAbove
>Pivot
> (
> Sum(count)
> FOR Choice2 IN
> ('YES', 'NO')
> )
>I get
>2 lines
>Question choice yes no
>-- -- -- --
>are you happy yes 14 null
>are you happy yes null 6
>are you happy no 7 null
>are you happy no null 15
>
>Any Ideas would be appreciated
Hi Troutbum,
I don't really understand yoour question. Is the output above what you
get or what you want? If it is what you currently get, then how do you
want it? And if it's what you want, then please explain how you get at
this output from the input - to me, a two-row output would make much
more sense.
I tried to reproduce your problem - after correcting some errors in the
query, I didn't get the result you quote above:
CREATE TABLE TableAbove
(cnt int NOT NULL,
question varchar(15),
choice char(3),
question2 varchar(15),
choice2 char(3))
go
INSERT INTO TableAbove (cnt, question, choice, question2, choice2)
SELECT 7, 'are you happy', 'no', 'are you ', 'yes'
UNION ALL
SELECT 14, 'are you happy', 'yes', 'are you ', 'yes'
UNION ALL
SELECT 6, 'are you happy', 'yes', 'are you ', 'no'
UNION ALL
SELECT 15, 'are you happy', 'no', 'are you ', 'no'
go
Select * from TableAbove
Pivot
(
Sum(cnt)
FOR choice2 IN
([yes], [no])
) AS p
go
DROP TABLE TableAbove
go
Result:
question choice question2 yes no
-- -- -- -- --
are you happy no are you 7 15
are you happy yes are you 14 6
Hugo Kornelis, SQL Server MVP
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment