gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:48:07 26 4
gpt4 key购买 nike

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

关于sql - 如何使用 CASE 语句在 SQL Server 中创建数据透视查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12723872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com