3

这是我在 mssql 下面的查询

declare @cars as table (
 owners tinyint,
 attribute varchar(20),
 value varchar(20)
)
insert into @cars(owners, attribute, value)
values      (1, 'Make', 'VW'),
            (1, 'Model', 'Rabbit'),
            (1, 'Color', 'Gold'),
            (1, 'Make', 'V'),
            (1, 'Model', 'Rabbi'),
            (1, 'Color', 'Goldddd'),
            (2, 'Make', 'Jeep'),
            (2, 'Model', 'Wrangler'),
            (2, 'Color', 'Gray')


            select * from @cars


  select pvt.owners, pvt.Make, pvt.Model, pvt.Color
from @cars c
pivot (
 min(value)
 for attribute in ([Make],[Model],[Color])
) pvt

以上回报

业主制作模型颜色

  1     v    rabbi gold

  2     jeep wrangler gray

但我需要像这样回来

业主制作模型颜色

  1     v    rabbi gold
  1     vw   rabbit golddd
  2     jeep wrangler gray

 how is possible?
4

1 回答 1

1

您需要在数据中添加一个附加字段,为每个所有者/属性组合提供唯一值:

SELECT  pvt.owners, pvt.Make, pvt.Model, pvt.Color
FROM    (   SELECT  Owners, 
                    Attribute, 
                    Value, 
                    RowNum = ROW_NUMBER() OVER(PARTITION BY Owners, Attribute ORDER BY Value)
            FROM    @Cars
        ) c
        PIVOT
        (   MIN(Value)
            FOR Attribute IN ([Make], [Model], [Color])
        ) pvt
ORDER BY Owners, Make, Model, Color;

这里的关键不仅仅是传递@cars给枢轴,子查询添加了一个额外的列来使表被透视:

Owners  Attribute   Value   RowNum
1       Color       Gold        1
1       Color       Goldddd     2
1       Make        V           1
1       Make        VW          2
1       Model       Rabbi       1
1       Model       Rabbit      2
2       Color       Gray        1
2       Make        Jeep        1
2       Model       Wrangler    1

因此,现在有一个额外的列可以区分GoldGoldddd例如,将它们强制到数据透视输出中的不同行上。

你会遇到问题,但如果所有属性都没有重复,如果缺少数据,你最终会得到 NULL,例如,如果你(1, 'Color', 'Goldddd')要从数据中删除值,那么输出将是:

owners  Make    Model       Color
1       V       Rabbi       Gold
1       VW      Rabbit      NULL
2       Jeep    Wrangler    Gray

SQL Fiddle 示例

于 2013-09-30T12:21:40.140 回答