如何使用CASE语句在SQL Server中创建透视查询?

时间:2012-10-04 09:06:05

标签: sql sql-server

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

3 个答案:

答案 0 :(得分:12)

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

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

答案 1 :(得分:3)

试试这个:

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 demo

答案 2 :(得分:-2)

试试这个:

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