[Solved] Rows to columns in SQL being one of the columns a count
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

Rows to columns in SQL being one of the columns a count

Database type:

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! : ).

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
CREATE INDEX original_idx_ma ON Original (MA);
The optimized query:
SELECT
        Original.MA,
        Original.SN,
        count(*) 
    FROM
        Original 
    WHERE
        Original.MA = 'AB' 
    GROUP BY
        Original.MA

Related Articles



* original question posted on StackOverflow here.