如何在 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) |
相关文章