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! : ).
Edit: You can’t use
COUNT2in the way you intend because later columns in the select list cannot refer to aliases of previous columns. SoCOUNT2has 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 missinggroup bycolumns, and then it works:http://www.sqlfiddle.com/#!3/41c79/7