Reputation: 21048
Good afternoon,
I am trying to use CASE like in this question to transpose rows to columns:
Rows to columns SQL Server query
However in my case I don't have a column with information it's a count of data.
I obtain the data with this query:
select MA, SN, count(*)
from Original
where MA = 'AB'
group by MA
Result of the query:
MA SN COUNT
AB TEXTA 6
AB TEXTB 5
AB TEXTC 3
AB TEXTD 4
table Original
MA SN
AB TEXTA
AB TEXTA
AB TEXTA
AB TEXTA
AB TEXTA
AB TEXTA
.
.
.
AB TEXTD
AB TEXTD
table Result:
MA TEXTA TEXTB TEXTC TEXTD
AB 6 5 3 4
And this is my current query:
select MA,
count(*) as 'COUNT2',
MAX(CASE WHEN SN = 'TEXTA' THEN COUNT2 end) as TEXTA1,
MAX(CASE WHEN SN = 'TEXTB' THEN COUNT2 end) as TEXTB1,
MAX(CASE WHEN SN = 'TEXTC' THEN COUNT2 end) as TEXTC1,
MAX(CASE WHEN SN = 'TEXTD' THEN COUNT2 end) as TEXTD1,
from Original
where MA= 'AB'
group by MA
WHat am I doing horribly wrong in the query?. And can someone please explain why in the question I posted it works but not with the count?. Thank you! : ).
Upvotes: 1
Views: 459
Reputation: 56769
Edit: You can't use COUNT2
in the way you intend because later columns in the select list cannot refer to aliases of previous columns. So COUNT2
has no meaning anywhere else in the query, unless you convert that part into a subquery (or cte) and then refer to it.
So, with your updated schema, it makes sense that you will need a subquery to do the counts. Essentially drop your first query as a subquery to the second query (in replace of Original
), and then add a few missing group by
columns, and then it works:
select MA,
MAX(CASE WHEN SN = 'TEXTA' THEN COUNT2 end) as TEXTA1,
MAX(CASE WHEN SN = 'TEXTB' THEN COUNT2 end) as TEXTB1,
MAX(CASE WHEN SN = 'TEXTC' THEN COUNT2 end) as TEXTC1,
MAX(CASE WHEN SN = 'TEXTD' THEN COUNT2 end) as TEXTD1
from (
select MA, SN, count(*) as COUNT2
from Original
where MA = 'AB'
group by MA, SN
) Original
where MA= 'AB'
group by MA
http://www.sqlfiddle.com/#!3/41c79/7
Upvotes: 4