0

考虑以下输入

Country1    Country2
A   Z
B   Y
C   X
D   W
X   C
W   D
A   Z

我想将往返视为一个数据进行分组。例如:将 C 到 X 和 X 到 C 视为 1。

Country1    Country2    Count of Trip
A   Z   2
B   Y   1
C   X   1
D   W   1

我如何在查询中将往返行程组合在一起。

4

2 回答 2

2
with cte as (
    select
        case when Country1 < Country2 then Country1 else Country2 end as Country1,
        case when Country1 < Country2 then Country2 else Country1 end as Country2
    from Table1
)
select
    Country1, Country2, count(*)
from cte
group by Country1, Country2

sql fiddle demo

于 2013-08-23T11:53:03.093 回答
1

您可以使用相关子查询消除往返行程,然后进行简单的分组:

SELECT 
  t1.Country1, 
  t1.Country2,
  COUNT(*) AS Trips
FROM Table1 t1
WHERE NOT EXISTS 
  (
    SELECT * FROM Table1 t2
    WHERE t1.Country1 = t2.Country2 
      AND t1.Country2 = t2.Country1
      AND t1.Country1 > t1.Country2
   )
GROUP BY t1.Country1, t1.Country2

SQLFiddle 演示

于 2013-08-23T13:14:49.533 回答