ANSI SQL用于转换列中的行

时间:2016-09-09 20:24:14

标签: mysql sql sql-server oracle ansi

我正在尝试根据以下数据转换列中的行:

Select EvolutionOrder, Age from Product where ProductID = 1 

EvolutionOrder Age
-------------- ----
             1 0012
             2 1324
             3 2536
             4 3700

Select EvolutionOrder, Age from Product where ProductID = 2 

EvolutionOrder Age
-------------- ----
             1 QUEE
             1 HIVE

我需要结果:

Product Age1 Age2 Age3 Age4 Age5
------- ---- ---- ---- ---- ----
      1 0012 1324 2536 3700 NULL
      2 QUEE HIVE NULL NULL NULL

我尝试使用PIVOT,但没有奏效,因为Age Column的聚合函数消失了值

SELECT ProductID,
    [1] AS Age1,
    [2] AS Age2,
    [3] AS age3,
    [4] AS age4
FROM Product
PIVOT (MAX(Age) FOR EvolutionOrder IN ([1], [2], [3], [4])) piv;

我得到了:

ProductID Age1 Age2 age3 age4
--------- ---- ---- ---- ----
1         0012 1324 2536 3700
2         QUEE NULL NULL NULL  --> HIVE Vanished

我得到的另一种方法是运行以下查询:

with vFX1 as (Select Age Age1 from Product  
                where ProductID = 1 and EvolutionOrder = 1)
   , vFX2 as (Select Age Age2 from Product  
                where ProductID = 1 and EvolutionOrder = 2)
   , vFX3 as (Select Age Age3 from Product  
                where ProductID = 1 and EvolutionOrder = 3)
   , vFX4 as (Select Age Age4 from Product  
                where ProductID = 1 and EvolutionOrder = 4)
   , vFX5 as (Select Age Age5 from Product  
                where ProductID = 1 and EvolutionOrder = 5)
select * from vFX1 Left outer Join vFX2 on 1=1
                   Left outer Join vFX3 on 1=1
                   Left outer Join vFX4 on 1=1
                   Left outer Join vFX5 on 1=1

我不喜欢这个解决方案,因为我需要多次运行同一个表并消失数据。

如果只使用一个ANSI sql smartest查询,我怎么能这样做?

在脚本下面创建数据:

Create table Product
(ProductID      Int
,EvolutionOrder Int
,Age            Char(4))

Insert into Product values (1,1,'0012');
Insert into Product values (1,2,'1324');
Insert into Product values (1,3,'2536');
Insert into Product values (1,4,'3700');
Insert into Product values (2,1,'QUEE');
Insert into Product values (2,1,'HIVE');

谢谢

注意:由于获得帮助而更新

2 个答案:

答案 0 :(得分:0)

语法略有不同,请看一下:

Select [1] Age1, [2] Age2, [3] Age3, [4] Age4, [5] Age5
from Product
PIVOT (MAX(Age) for EvolutionOrder in ([1],[2],[3],[4],[5])) P

不要害怕聚合。如果只有一个值,那么MIN或MAX将等于该值。

答案 1 :(得分:0)

未正确选择列是一个问题。您绝对可以在CHARVARCHAR列上使用汇总。

CREATE TABLE Product (
    ProductID int,
    EvolutionOrder int,
    Age char(4)
)

INSERT INTO Product
    VALUES (1, 1, '0012');
INSERT INTO Product
    VALUES (1, 2, '1324');
INSERT INTO Product
    VALUES (1, 3, '2536');
INSERT INTO Product
    VALUES (1, 4, '3700');

SELECT
    ProductID,
    [1] AS Age1,
    [2] AS Age2,
    [3] AS age3,
    [4] AS age4
FROM Product
PIVOT (MAX(Age) FOR EvolutionOrder IN ([1], [2], [3], [4])) piv;

DROP TABLE Product