SQL中的表转换逻辑

时间:2017-10-29 14:26:22

标签: sql sql-server

我有一张桌子T:

CREATE TABLE T 
(
     id INT,
     type VARCHAR(200),
     type_value VARCHAR(10),
     value  VARCHAR(200)
);

INSERT INTO T VALUES (1, 'RoomColor', 'room1', 'yellow');
INSERT INTO T VALUES (1, 'RoomColor', 'room2', 'red');
INSERT INTO T VALUES (2, 'RoomColor', 'room1', 'blue');
INSERT INTO T VALUES (2, 'RoomColor', 'room1', 'pink');
INSERT INTO T VALUES (3, 'RoomColor', 'room1', 'white');
INSERT INTO T VALUES (3, 'RoomColor', 'room2', 'grey');
INSERT INTO T VALUES (3, 'RoomColor', 'room2', 'brown');
INSERT INTO T VALUES (4, 'RoomColor', 'room3', 'green');

我需要将其转换为:

id   BedRoomColor    DiningRoomColor 
------------------------------------------- 
 1    yellow           red
 2    blue             pink
 3    white            grey
 4    green            null   

转型背后的逻辑:

  1. 如果有两个以上的房间 type_value ,则丢弃第三个房间type_value
  2. 对于相同的ID,如果有多个房间type_value(例如 room1,room1 room2,room2 room1,room2 )然后使用第一个type_value创建为 BedRoomColor ,使用第二个type_value创建 DiningRoomColor
  3. 如果id只有1个房间type_value (例如room1或room2或room3),那么对应的值(红色,绿色,黄色等)将是放在BedRoomColor和DiningRoomColor中将 null
  4. 我正在努力解决这个问题几天。任何人都可以帮助我。

    由于

3 个答案:

答案 0 :(得分:2)

您可以使用此脚本

if(sum(Example$Col1 < -5) > 0){
    Example[Example$Col1 < -5,]$Col1 <- 0
}

结果:

;WITH CTE AS (
SELECT *, RN = ROW_NUMBER() OVER(PARTITION BY id ORDER BY type_value) FROM T 
)
SELECT id, [1] BedRoomColor, [2] DiningRoomColor FROM
    (SELECT id,value, RN FROM CTE  ) SRC
    PIVOT (MAX(value) FOR RN IN ([1], [2]) ) AS PVT

答案 1 :(得分:1)

试试这个:

with tmp as (
select T.*, rownumber() over(patition by id order by type_value) rang
from T
)
select f1.id, f1.value as BedRoomColor, f2.value as DiningRoomColor 
from tmp f1
left outer join tmp f2 on f1.id=f2.id and f2.rang=2 
where f1.rang=1

答案 2 :(得分:1)

另一种方法是在查询中添加type

;with tt as (
    select *,
        row_number() over (partition by [type], id  order by type_value) rn
        --                              ^^^^^^ I add type to support other types if there is
    from t
)
select id,
    max(case when [type] = 'RoomColor' and rn = 1 then [value] end) 'BedRoomColor',
    max(case when [type] = 'RoomColor' and rn = 2 then [value] end) 'DiningRoomColor'
from tt
group by id;

SQL Server Fiddle Demo