Col1 仅包含 X 和 Y。
Col1 Col2
X abc
Y pqr
X pqr
X mnq
Y cxr
我想让它像这样:
X Y Col2
Yes Yes pqr
Yes No abc
Yes No mnq
No Yes cxr
我应该写什么 SQL 查询?
Col1 仅包含 X 和 Y。
Col1 Col2
X abc
Y pqr
X pqr
X mnq
Y cxr
我想让它像这样:
X Y Col2
Yes Yes pqr
Yes No abc
Yes No mnq
No Yes cxr
我应该写什么 SQL 查询?
使用SQL PIVOT 运算符的解决方案:
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;
试试这个:
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