如何在查询级别删除交叉重复项

时间:2014-10-21 10:04:32

标签: sql

from_station     to_station     distance      fare
---------------------------------------------------
delhi            banglore          250        3000
bombay           delhi             200        2000
bombay           kokatta           350        3500
delhi            bombay            200        2000
delhi            kokatta           250        3000
kokatta          delhi             250        3000
kokatta          bombay            350        3500
banglore         delhi             250        3000

以上数据我只在查询级别

需要以下过滤行

我的所需输出如下所示:

from_station     to_station     distance      fare
--------------------------------------------------
banglore         delhi             250        3000
bombay           delhi             200        2000
bombay           kokatta           350        3500
delhi            kokatta           250        3000

1 个答案:

答案 0 :(得分:3)

您可以使用case

在标准SQL中执行此操作
select (case when from_station < to_station then from_station else to_station end) as from_station,
       (case when from_station < to_station then to_station else from_station end) as to_station,
       max(distance) as distance, max(far) as fare
from table t
group by (case when from_station < to_station then from_station else to_station end),
         (case when from_station < to_station then to_station else from_station end);

某些数据库提供greatest()least()函数,这使其更具可读性:

select least(from_station, to_station) as from_station,
       greatest(from_station, to_station) as to_station,
       max(distance) as distance, max(far) as fare
from table t
group by least(from_station, to_station), greatest(from_station, to_station);