1

我有两个名为PRODUCTDETAIL

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
4

4 回答 4

5

这种数据转换称为 aPIVOT并且从 SQL Server 2005 开始,有一个函数可以将数据从行转换为列。

有几种方法可以做到这一点,具体取决于您是否有静态数量的值要转置到列中。所有这些都涉及向row_number()数据添加 a,以便您可以返回任何产品的多行。

您可以将聚合函数与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

请参阅带有演示的 SQL Fiddle

您可以使用以下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:

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

所有查询的结果是:

|    X |      Y |      Z |
--------------------------
| good |    bad |  worse |
|  bad | (null) | (null) |
于 2013-02-28T10:56:02.937 回答
1
This is your query.
    select p.product, d.detail from product p
inner join detail d on  p.product = d.product
于 2013-02-28T10:49:03.970 回答
0

查看 SQL Join 语句。这篇博文很好地解释了它。

于 2013-02-28T10:37:44.277 回答
0
select d.product, d.detail from detail d
join product p on d.product = p.product
于 2013-02-28T10:39:11.410 回答