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
答案 0 :(得分:3)
您可以使用case
:
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);