如何使用CASE语句在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查询

解决方法

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

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...