SQL行只有两列的列

时间:2015-10-08 09:37:47

标签: sql pivot rows

这个问题已被多次询问,但我无法将我到目前为止所读到的任何答案都与我的确切问题联系起来。我们说我的原始表有2列。

Brand      Type
Mercedes   Sedan
BMW        Sedan
Mercedes   SUV
Jeep       SUV
VW         Sedan
VW         Small Family

我想格式化原始表格,如下所示

[Sedan]    [SUV]       [Small Family]
BMW        Mercedes    VW    
Mercedes   Jeep        NULL   
VW         NULL        NULL

在任何类型的环境(即SQL服务器,Oracle,DB2)中,是否可以使用任何类型的SQL,有或没有PIVOT功能?

4 个答案:

答案 0 :(得分:0)

要直接回答您的问题,最简单的方法是使用PIVOT。 ,如果要将行设置为柱状,或将列设置为行,则解决方案仅为PIVOT

SQL Server有一个PIVOT函数可供您实现,此链接可以帮助您:Convert Rows to columns using 'Pivot' in SQL Server

修改

PIVOT示例:

    SELECT [Sedan], [SUV], [Small Familiy] FROM
        (
            SELECT ROW_NUMBER()
            OVER (PARTITION BY [TYPE] ORDER BY Brand) RowNum, Brand, [Type] FROM tblCar
        ) AS src
        PIVOT 
        (
            MIN(Brand) FOR [Type] IN ([Sedan], [SUV], [Small Familiy])
        ) AS pvt

SQL Fiddle sample for PIVOT

希望这有帮助。

答案 1 :(得分:0)

Select 
    (CASE Type = 'Sedan' 
        then Brand 
        else null 
    end) Sedan, 
    (CASE Type = 'SUV' 
        then Brand 
        else null 
    end) SUV, 
    (CASE Type = 'Small Family' 
        then Brand 
        else null 
    end) SmallFamily 
FROM table

答案 2 :(得分:0)

DECLARE @Table1 TABLE 
    (Brand varchar(8), Type varchar(12))
;

INSERT INTO @Table1
    (Brand, Type)
VALUES
    ('Mercedes', 'Sedan'),
    ('BMW', 'Sedan'),
    ('Mercedes', 'SUV'),
    ('Jeep', 'SUV'),
    ('VW', 'Sedan'),
    ('VW', 'Small Family')
;


Select [Sedan],[SUV],[Small Family] FROM (
select ROW_NUMBER()OVER(PARTITION BY TYPE ORDER BY TYPE)RN,Brand, Type from @Table1)T
PIVOT (
MAX(brand) FOR TYPE IN ([Sedan],[SUV],[Small Family]))P

答案 3 :(得分:0)

请尝试以下操作:

select Sedan, SUV, [Small Family]
from
(
  select ROW_NUMBER()OVER(PARTITION BY TYPE ORDER BY TYPE)RN,Brand, Type from Cars)Cars
pivot
(
  max(Brand)
  for [Type] in (Sedan, SUV, [Small Family])
) piv;