如何加入那些sql语句+可能的行到列转换

时间:2013-09-14 15:02:22

标签: sql sql-server

所以,假设我有这三个表(数据不符合逻辑)。

所有者

ID_OWNER | NAME | SURNAME 
1    John    Carter
2    Chris   Collins
3    Wright   Doe

CARS

ID_OWNER | MODEL | MODEL_TYPE
1     |   FORD_FOCUS  |  FAMILY
1     |  TRANSPORTER_VW   |   TRANSPORTER
1     |   VOLVO_S60     | null
2     |    VOLVO_S80    |  null

价格

MODEL_TYPE| PRICE1
FAMILY | 2
TRANSPORTER | 4

所以到目前为止我有两个SQL语句。第一个搜索所有者:

SELECT 
    o.NAME, o.SURNAME 
FROM
    OWNERS o 
WHERE
    o.NAME='John';

第二个搜索所有者'John'的型号和价格。由于MODEL_TYPE可能为空值,我使用LEFT JOIN。我有三排。

SELECT
    CARS.ID_OWNER, CARS.MODEL, CARS.MODEL_TYPE, PRICE.PRICE1 
FROM
    CARS 
LEFT JOIN
    PRICE ON CARS.MODEL_TYPE = PRICE.MODEL_TYPE
WHERE
    CARS.ID_OWNER = 1;

结果:

ID_OWNER | MODEL          | MODEL_TYPE  | PRICE1 | NAME |SURNAME
    1    | FORD FOCUS     | FAMILY      |   2    | JOHN | CARTER
    1    | TRANSPORTER_VW | TRANSPORTER |   4    | JOHN | CARTER
    1    | VOLOV_S60      | null        | null   | JOHN | CARTER

现在,我需要在一个SQL查询中将John Carter拥有的所有汽车及其型号和价格的结果放在一行中。我被卡住了。

有可能吗?我读到了枢轴和其他可能性,但没有找到合适的答案。如何组合它并将结果合并成一行而不是三行?

1 个答案:

答案 0 :(得分:0)

如果每个人的车数不超过n辆,您可以这样做:

with cte as (
    select
        o.NAME, o.SURNAME,
        c.MODEL,
        c.MODEL_TYPE,
        p.PRICE1,
        row_number() over(partition by o.ID_OWNER order by MODEL) as rn
    from OWNERS as o
        left outer join CARS as c on c.ID_OWNER = o.ID_OWNER
        left outer join PRICE as p on p.MODEL_TYPE = c.MODEL_TYPE
)
select
    c.NAME, c.SURNAME,
    max(case when c.rn = 1 then c.MODEL end) as MODEL1,
    max(case when c.rn = 1 then c.MODEL_TYPE end) as MODEL_TYPE1,
    max(case when c.rn = 1 then c.PRICE1 end) as PRICE11,
    max(case when c.rn = 2 then c.MODEL end) as MODEL2,
    max(case when c.rn = 2 then c.MODEL_TYPE end) as MODEL_TYPE2,
    max(case when c.rn = 2 then c.PRICE1 end) as PRICE12,
    max(case when c.rn = 3 then c.MODEL end) as MODEL3,
    max(case when c.rn = 3 then c.MODEL_TYPE end) as MODEL_TYPE3,
    max(case when c.rn = 3 then c.PRICE1 end) as PRICE13
from cte as c
group by c.NAME, c.SURNAME

<强> sql fiddle demo

对于任意数量的汽车来说,这很容易作为动态SQL执行,但我不确定您是否可以在客户端使用此查询,通常更容易使用行(而不是列)