SQL在所有列中选择唯一的表行

时间:2014-02-04 09:59:20

标签: sql postgresql amazon-redshift

我有一张表格,其结果如下所示

total_passengers origin_city_name  dest_city_name   year
----------------------------------------------------------------
2926589          New York          Chicago          2009
2926589          Chicago           New York         2009
2876933          Los Angeles       San Francisco    2009
2876933          San Francisco     Los Angeles      2009

如何删除冗余行 - 2& 4。

由于

3 个答案:

答案 0 :(得分:4)

如果您不关心在没有第二行时是否可以交换原点和来源:

SELECT DISTINCT
  total_passengers,
  CASE WHEN origin_city_name > dest_city_name 
       THEN dest_city_name 
       ELSE origin_city_name
  END,
  CASE WHEN origin_city_name < dest_city_name 
       THEN dest_city_name
       ELSE origin_city_name
  END,
  year
FROM tab
;

答案 1 :(得分:1)

为查询添加WHERE子句,因此您不会获得反向的原始目标记录:

WHERE origin_city_name < dest_city_name

答案 2 :(得分:0)

dnoeth's answer略有不同:

SELECT DISTINCT
total_passengers, 
LEAST(origin_city_name, dest_city_name) AS origin_city_name,
GREATEST(origin_city_name, dest_city_name) AS dest_city_name,
year
FROM yourtable;

here's the fiddle