sql - 如何在sql server中旋转表时返回多行

标签 sql sql-server pivot

这是我在 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?

最佳答案

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

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

Example on SQL Fiddle

关于sql - 如何在sql server中旋转表时返回多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19093913/

相关文章:

c# - 枢轴应用程序 (WP7) 中的动画控制

mysql - 如何在 mysql 中编写多个选择查询,即一个查询返回一些 id,然后我将根据返回的 id 编写选择查询?

sql - mysql日期时间比较

php + sql server 登录和 session

sql - MS SQL Server,多次插入

C++ SQLExecDirect INSERT 不起作用

sql-server - 哪个更快?多个 DELETE 语句或单个 DELETE 语句使用 "IN (' x', '' y')"

many-to-many - Eloquent ORM/Laravel - 使用自定义数据透视表结构

c# - 为一张表中的嵌套数据创建简化查询 (.NET Core)

Excel/数据透视表 : Is there any way to prevent the cells from moving when I filter information?