Col1 contains only X and Y.
Col1 Col2 X abc Y pqr X pqr X mnq Y cxr
I want to do it as follows:
XY Col2 Yes Yes pqr Yes No abc Yes No mnq No Yes cxr
What SQL query should I write?
Solution using SQL PIVOT operator :
SELECT Col2, case when X=0 then 'No' else 'Yes' end as X, case when Y=0 then 'No' else 'Yes' end as Y FROM MyTable PIVOT ( count(Col1) FOR Col1 IN ([X], [Y]) ) AS PivotTable;
try the following:
with cte as (select col2, min(col1)as X, min(col1) as Y, count(distinct col1) as cnt from your_table group by col2) select COL2, case when X='X' then 'Yes' else 'No' end X, case when Y='Y' OR cnt=2 then 'Yes' else 'No' end Y from cte
select col2,CASE WHEN COUNT(*)=1 then CASE WHEN min(col1)='X' then 'YES' else 'NO' end else 'YES' end as 'X', CASE WHEN COUNT(*)=1 then CASE WHEN min(col1)='Y' then 'YES' else 'NO' end else 'YES' end as 'Y' from MyTable group by col2
Source: https://habr.com/ru/post/926935/More articles:ServiceStack Backbone.Todos Removing 405 Not Allowed - c #Android emulator - DDMS "control emulator" is disabled during the operation of the emulator based on buildroid / virtualbox - androidHow to clear initialized resources if an exception is thrown from a constructor in C ++ - c ++Use a different setParameters.xml file? - msdeployProblems with matching spaces with MySql REGEX - regexHow to properly handle exceptions in constructors? - c ++DbContext.Entry performance issue - entity-framework-5Persistent Object in C # .NET Web Service - c #Is it possible to stop the Entity Framework "fixing" relationships after SaveChanges? - c #How to prevent duplicate entries during the update? - javaAll Articles