简体   繁体   中英

SQL Query pivoting or grouping

I have an issue in making a SQL query to sort out a datatable and dont know how to approach it. That is, i have a datatable that looks like this:

在此处输入图像描述

And i would like to query it like this:

在此处输入图像描述

For retrieving the initial datatable i'm using following query:

SELECT top 100 replace(convert(varchar, db1.Create_On,101),'/','') + replace(convert(varchar, db1.Create_On,108),':','') as 'Creation_Date', db1.PSP, db1.Create_on, db1.Create_by, db1.Language, db1.Name, db1.FirstName, db2.*
from db1 INNER JOIN
     db2
     ON (db1.IB_H_Id = db2.IB_H_Id) AND (db1.Create_on = db2.Create_on) AND (db1.Create_by = db2.Create_by)
WHERE (((db1.IB_H_Id)='CLA_052') AND ((db1.SendMail) Like '') AND ((db2.Answer_Char) = 'Email') OR ((db2.Answer_Char) = 'Card'))
order by [Creation_Date];

Now i don't know how to approach it whether with group by or pivot. Thanks for the help!

You can use conditional aggregation:

with t as (
      <your query here>
     )
select column1,
       max(case when column2 = 1 then column3 end) as col2_1,
       max(case when column2 = 2 then column3 end) as col2_2,
       max(case when column2 = 3 then column3 end) as col2_3
from t
group by column1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM