November 12, 2012 at 12:22 pm
Hi all,
I have to make the following, but I've had no luck getting it done. Can you please help? Thanks in advance.
Before:
Col1 Col2 Col3 Col4
1 2 A 1
1 2 B 2
1 2 C 3
After:
Col1 Col2 Col3_1 Col3_2 Col3_3
1 2 A B C
The data includes only 3 rows max for combination of Col1 and Col2. And the results have to be ordered using Col4, Ascending. Thanks again.
There can only be
November 12, 2012 at 12:54 pm
November 12, 2012 at 1:05 pm
That's exactly what I am trying right now! 🙂
I got this so far:
SELECT col1,
col2,
CASE col4
WHEN 1 THEN col3
ELSE NULL
END AS col3_1,
CASE col4
WHEN 2 THEN col3
ELSE NULL
END AS col3_2,
CASE col4
WHEN 3 THEN col3
ELSE NULL
END AS col3_3
FROM table1
GROUP BY col1,
col2
However, when I run this I get the following errors:
Msg 8120, Level 16, State 1, Line 1
Column col3 is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Msg 8120, Level 16, State 1, Line 1
Column col4 is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
I'm working on it, but if you have the solution, please don't hesitate to post it. Thanks for your input by the way.
November 12, 2012 at 1:07 pm
Forgot, I have also tried PIVOT.
November 12, 2012 at 2:07 pm
I figured it out, just like you said, I used MAX around each CASE statement and it ran like a charm. Thanks!
November 12, 2012 at 5:03 pm
shahgols (11/12/2012)
I figured it out, just like you said, I used MAX around each CASE statement and it ran like a charm. Thanks!
Outstanding! Would you post your solution so that others may learn from it? Thanks!
--Jeff Moden
Change is inevitable... Change for the better is not.
November 13, 2012 at 10:50 am
GOOD idea, sure, here is the code:
SELECT col1,
col2,
Max(CASE col4
WHEN 1 THEN col3
ELSE NULL
END) AS col3_1,
Max(CASE col4
WHEN 2 THEN col3
ELSE NULL
END) AS col3_2,
Max(CASE col4
WHEN 3 THEN col3
ELSE NULL
END) AS col3_3
FROM table1
GROUP BY col1,
col2
And in case you are wondering, formatting of the above SQL was done at this page (with whom I have no affiliation with):
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply