How to create query in sql to pivot data?(如何在 sql 中创建查询以透视数据?)
问题描述
我有两个名为 PRODUCT 和 DETAIL
TABLE: PRODUCT
slno product
1 x
2 y
3 z
TABLE: DETAIL
product detail
x good
y bad
z worse
x bad
我需要输出为
TABLE
X Y Z
good bad worse
bad
推荐答案
这种数据转换称为 PIVOT 从 SQL Server 2005 开始,有一个函数可以将数据从行转换为列.
This data transformation is known as a PIVOT and starting in SQL Server 2005 there is a function to convert the data from rows to columns.
有几种方法可以做到这一点,具体取决于您是否有静态数量的值要转置到列中.所有这些都涉及将 row_number() 添加到数据中,以便您可以返回任何产品的多行.
There are several ways that this can be done depending on whether or not you have a static number of values to transpose into columns. All of them involve adding a row_number() to the data so you can return the multiple rows of any of the products.
您可以将聚合函数与 CASE 表达式一起使用:
You can use an aggregate function with a CASE expression:
select
max(case when product = 'x' then detail end) x,
max(case when product = 'y' then detail end) y,
max(case when product = 'z' then detail end) z
from
(
select p.product, d.detail,
row_number() over(partition by p.product order by p.slno) rn
from product p
inner join detail d
on p.product = d.product
) src
group by rn
参见SQL Fiddle with Demo
您可以使用PIVOT功能:
select x, y, z
from
(
select p.product, d.detail,
row_number() over(partition by p.product order by p.slno) rn
from product p
inner join detail d
on p.product = d.product
) src
pivot
(
max(detail)
for product in (x, y, z)
) piv
参见 SQL Fiddle with Demo.
如果您有未知数量的值(在本例中为产品)转换为列,那么您将需要使用动态 SQL:
If you have an unknown number of values (products in this case) to turn into columns, then you will want to use dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(product)
from product
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ' + @cols + ' from
(
select p.product, d.detail,
row_number() over(partition by p.product order by p.slno) rn
from product p
inner join detail d
on p.product = d.product
) x
pivot
(
max(detail)
for product in (' + @cols + ')
) p '
execute(@query)
参见 SQL Fiddle with Demo
所有查询的结果是:
| X | Y | Z |
--------------------------
| good | bad | worse |
| bad | (null) | (null) |
这篇关于如何在 sql 中创建查询以透视数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 sql 中创建查询以透视数据?
基础教程推荐
- 带有WHERE子句的LAG()函数 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
