0

在此处输入图像描述

我有这个数据库。它不包含所有表格,但对于我的问题,图片中包含的内容就足够了。

该数据库是为运输公司设计的。

所以,我有一个预订。任何预订都可以有多个地址。这些类型是(routing_type:上车、下车、下车)。我的地址是街道地址或机场。

内部路由表使用 address_id 或 airport_id 来判断路由的类型。如果 airport_id 有一个数字,则 address_id 为 NULL。

在我的 booking_routing 表中,我有与特定预订的路由类型一样多的条目。如果我有 3 个特定预订的地址,我将在 booking_routing 中有 3 个条目(可能是 Pick-up,然后是 Stop,然后是 Drop-off)。通常只需要两个地址,上车下车。

问题:我尝试创建一个查询,其中我将在同一行显示我的接送点和预订中的其他字段。

例子:

Booking_ID Account_ID ... 取车 下车
121 32 1 Main St IAD, AA-322

现在我只设法让他们在两行上使用 LEFT JOIN。像这样:
Booking_ID Account_ID ... Address_Type Address
121 32 Pick_up 1 Main St
121 32 Drop-Off IAD, AA-322

SELECT   
b.booking_id as ID, a.account_id as Acc_ID, 
MAX(CASE WHEN br.routing_type_id = 1 THEN -- 1=pick-up
    Concat(ad.address_line1, " ", api.code, " ", aii.code, "-", ap.flight_number) END) as Pick_up,
    MAX(CASE WHEN br.routing_type_id = 4 THEN  -- 4=drop-off
             Concat(ad.address_line1, " ", api.code, " ", aii.code, "-", ap.flight_number) END) as Drop_off

FROM booking b
left JOIN account a ON b.account_id = a.account_id
left join booking_routing br ON b.booking_id = br.booking_id
left join routing r ON br.routing_id = r.routing_id
left join routing_type rt ON br.routing_type_id = rt.routing_type_id
left join address ad ON r.address_id = ad.address_id
left join airport ap ON r.airport_id = ap.airport_id
left join airport_info api ON ap.airport_info_id = api.airport_info_id
left join airline_info aii ON ap.airline_info_id = aii.airline_info_id

group by b.booking_id, a.account_id;
4

1 回答 1

0

MAX您可以通过使用and来实现这一点CASE

SELECT Booking_Id, 
   Account_Id, 
   MAX(CASE WHEN Address_Type = 'Pick_up' THEN Address END) Pick_Up,
   MAX(CASE WHEN Address_Type = 'Drop-Off' THEN Address END) Drop_Off
FROM YourTables...
GROUP BY Booking_Id, Account_Id

SQL 小提琴演示

于 2013-03-30T02:20:47.377 回答