2

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

拥有者

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

汽车

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';

第二个搜索所有者“约翰”的型号和价格。由于 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 拥有的所有汽车及其型号类型和价格的结果。我被困住了。

是否可以?我阅读了有关枢轴和其他可能性的信息,但没有找到合适的答案。如何将它合并并将结果合并为一行而不是三行?

4

1 回答 1

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 很容易做到这一点,但我不确定您是否可以在客户端使用此查询,使用行(而不是列)通常更容易

于 2013-09-14T15:29:43.943 回答