我有两个名为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
答案 0 :(得分:5)
此数据转换称为PIVOT
,从SQL Server 2005开始,有一个函数可以将数据从行转换为列。
根据您是否有静态数量的值转换为列,有几种方法可以实现。所有这些都涉及向数据添加row_number()
,以便您可以返回任何产品的多行。
您可以使用带有CASE
表达式的聚合函数:
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
您可以使用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:
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)
所有查询的结果是:
| X | Y | Z |
--------------------------
| good | bad | worse |
| bad | (null) | (null) |
答案 1 :(得分:1)
This is your query.
select p.product, d.detail from product p
inner join detail d on p.product = d.product
答案 2 :(得分:0)
查看SQL Join语句。 This blogpos很好地解释了它。
答案 3 :(得分:0)
select d.product, d.detail from detail d
join product p on d.product = p.product