6

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 查询?

4

3 回答 3

12

使用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;

运行示例:http ://www.sqlfiddle.com/#!3/5856d/14

于 2012-10-04T09:15:26.270 回答
4

试试这个:

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


SQL Fiddle 演示

于 2012-10-04T09:25:20.537 回答
-1

试试这个:

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 
于 2012-10-04T09:35:35.567 回答