如何从两列获得双向组合的数量?

时间:2017-08-08 21:10:23

标签: sql-server tsql aggregate-functions

我在一家货运公司工作,我们有兴趣计算一辆卡车在两个城市之间往哪两个方向行驶的次数。

我有一张表格,列出了每个旅程段的来源和目的地,例如:

Origin    Destination
City 1 City 2 City 2 City 1 City 3 City 4 City 2 City 1

我需要一个查询,告诉我城市1和城市2之间有三次旅行,城市3和城市4之间有一次旅行。非常感谢!

3 个答案:

答案 0 :(得分:3)

这是一种排序列的方法。当然,我将列名从输出更改为OriginDestination之外的其他内容,因为它们基本上将其转换为"路由"。或许只是concat他们就像a1ex07那样。如果您想改变它,我会将其标准化。

declare @table table (Origin varchar(16), Destination varchar(16))
insert into @table
values
('City 1','City 2'),
('City 2','City 1'),
('City 3','City 4'),
('City 2','City 1')

;with cte as(
select 
    case when Origin > Destination then Origin else Destination end as Origin
    ,case when Destination < Origin then Destination else Origin end as Destination
from
    @table)

select
    Origin
    ,Destination
    ,count(Origin + Destination) 
from 
    cte
group by
    Origin
    ,Destination

答案 1 :(得分:3)

我认为以下应该可以解决问题。

SELECT route , COUNT(1) FROM 
(
   SELECT 
   CASE WHEN Origin > Destination THEN Origin+'_'+Destination
   ELSE Destination+'_'+Origin 
   END AS route
   FROM table1
 )a
 GROUP BY route

答案 2 :(得分:0)

正如他们所说,如果你有正确的数据结构,你通常可以免费获得正确的算法。

我猜测您的架构包含类似于以下内容的表:

create table City
(
    id int primary key identity,
    name nvarchar(100) not null
)

create table TravelLog
(
    trip_id int primary key identity,
    origin int foreign key references City,
    destination int foreign key references City,
    check (origin <> destination)
)

因此,如果您将以下两个字段添加到TravelLog表中:

alter table TravelLog
    add 
        low as case when origin <= destination then origin else destination end persisted,
        high as case when origin >= destination then origin else destination end persisted

然后,您可以使用以下简单查询来获得所需内容:

with Q as
(
    select count (*) as trips, low, high from TravelLog group by low, high
)

select Q.trips, o.name point_A, d.name point_B from Q 
    inner join City o on o.id = Q.low
    inner join City d on d.id = Q.high

作为附带好处,您可以使用相同的查询按驱动程序,日期等进行过滤。