基于sql server中的两列对数据进行分组

时间:2013-08-23 11:50:27

标签: sql sql-server

考虑以下输入

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 DEMO