0

表A:

Brand     Product
------------------
A            X
A            XX
A            XXX
B            Y
B            YY
C            Z

我需要如下表所示的数据:

A      B      C
-------------------
X      Y      Z
XX     YY     NULL   
XXX    NULL   NULL   

如何在 Sql Server 2008 中做到这一点?

4

2 回答 2

3

我不相信 PIVOT 是您在这里寻找的。

从我可以看到您正在查看使用条目来生成行?

此外,PIVOT 使用聚合函数,所以我看不到这种情况发生。

你可以尝试的,就像

DECLARE @Table TABLE(
        Brand VARCHAR(10),
        Product VARCHAR(10)
)

INSERT INTO @Table SELECT 'A','X '
INSERT INTO @Table SELECT 'A','XX' 
INSERT INTO @Table SELECT 'A','XXX'
INSERT INTO @Table SELECT 'B','Y' 
INSERT INTO @Table SELECT 'B','YY' 
INSERT INTO @Table SELECT 'C','Z' 

;WITH Vals AS (
        SELECT  *,
                ROW_NUMBER() OVER(PARTITION BY Brand ORDER BY (SELECT NULL)) RID
        FROM    @Table
)
, RIDs AS (
        SELECT  DISTINCT
                RID
        FROM    Vals
)
SELECT  vA.Product [A],
        vB.Product [B],
        vC.Product [C]
FROM    RIDs r LEFT JOIN
        Vals vA ON  r.RID = vA.RID
                AND vA.Brand = 'A' LEFT JOIN
        Vals vB ON  r.RID = vB.RID
                AND vB.Brand = 'B' LEFT JOIN
        Vals vC ON  r.RID = vC.RID
                AND vC.Brand = 'C'
于 2012-08-17T04:34:19.063 回答
1

我知道这是一个较晚的条目,但这里有一种不同的方法来解决它:

DECLARE @Table TABLE(Brand VARCHAR(10), Product VARCHAR(10)) 
INSERT INTO @Table SELECT 'A','X ' 
INSERT INTO @Table SELECT 'A','XX'  
INSERT INTO @Table SELECT 'A','XXX' 
INSERT INTO @Table SELECT 'B','Y'  
INSERT INTO @Table SELECT 'B','YY'  
INSERT INTO @Table SELECT 'C','Z'  

SELECT [A],[B],[C] FROM (
SELECT row_number() over (partition by brand order by product) rn,  
Product, brand FROM @table
) as p
PIVOT(
  MAX(product) for Brand in ([A],[B],[C])
)as pvt 
于 2012-08-17T09:25:21.150 回答