这个问题已经在这里有一个答案:
- 获取各行栏目(SQL Server的动态PIVOT查询) 2个回答
我有两个表命名的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
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.
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.
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
See SQL Fiddle with Demo
You can use the PIVOT
function:
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
See SQL Fiddle with Demo.
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)
See SQL Fiddle with Demo
The result of all of the queries is:
| X | Y | Z |
--------------------------
| good | bad | worse |
| bad | (null) | (null) |
This is your query.
select p.product, d.detail from product p
inner join detail d on p.product = d.product
看看到SQL语句组合。 这blogpos牛逼很好地解释它。
select d.product, d.detail from detail d
join product p on d.product = p.product