跨越行的SQL总和"匹配"?

时间:2016-04-07 21:47:46

标签: sql sql-server tsql grouping

SQL问题:

我有一个包含3列的表格: From_City,To_City,Trip_Count 和4行:

+-----------+---------+------------+
| From_City | To_City | Trip_Count |
+-----------+---------+------------+
| Berlin    | London  |          2 |
| London    | Berlin  |          3 |
| Sydney    | Tokyo   |          4 |
| Tokyo     | Sydney  |          6 |
+-----------+---------+------------+

我想将城市之间的旅行总结为一个只有2行的新表:

+--------+------------+------------+
|  City  | Other_City | Trip_Count |
+--------+------------+------------+
| Berlin | London     |          5 |
| Sydney | Tokyo      |         10 |
+--------+------------+------------+

我无法弄清楚如何在SQL(最好是SQL Server)中实现这一点。有什么建议?谢谢!

注意:两个城市之间的顺序并不重要。无论是柏林 - 伦敦还是伦敦 - 柏林都可以。

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT CASE 
           WHEN From_City < To_City THEN From_City 
           ELSE To_City 
       END AS City,
       CASE 
           WHEN From_City >= To_City THEN From_City 
           ELSE To_City 
       END AS Other_City,
       SUM(Trip_Count) AS Trip_Count
FROM mytable
GROUP BY CASE WHEN From_City < To_City THEN From_City ELSE To_City END,
         CASE WHEN From_City >= To_City THEN From_City ELSE To_City END

答案 1 :(得分:0)

更新:正如FLICKER指出的那样;这在SQL Server中不起作用,因为SQL Server不能提供LEAST和GREATEST,也不提供SQLite中的MIN / MAX等类似功能。遗憾。

您获得了LEAST的第一个城市和GREATEST的另一个城市:

create table full_trips as
(
  select 
    least(from_city, to_city) as city,
    greatest(from_city, to_city) as other_city,
    sum(trip_count) as trip_count
  from trips
  group by least(from_city, to_city), greatest(from_city, to_city)
);