我为一家卡车运输公司工作,我们有兴趣了解其中一辆卡车在两个城市之间往返的方向。如何从两列中获得双向组合的数量?
我有列出每个行程段的起点和终点的表格,如:
Origin Destination
City 1 City 2 City 2 City 1 City 3 City 4 City 2 City 1
我需要一个查询,告诉我,有城市1和城市2和一个绊之间三趟城市3和城市4之间。非常感谢!
我为一家卡车运输公司工作,我们有兴趣了解其中一辆卡车在两个城市之间往返的方向。如何从两列中获得双向组合的数量?
我有列出每个行程段的起点和终点的表格,如:
Origin Destination
City 1 City 2 City 2 City 1 City 3 City 4 City 2 City 1
我需要一个查询,告诉我,有城市1和城市2和一个绊之间三趟城市3和城市4之间。非常感谢!
我认为以下几点应该能够解决问题。
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
它确实!非常感谢! – CBode
这是一种通过对列进行排序的方式。当然,我会将输出中的列名更改为Origin
和Destination
以外的列名,因为基本上它们已经变成了“路线”。也许只是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
谢谢非常!这绝对是诀窍。 – CBode
正如他们所说,如果您拥有正确的数据结构,您通常可以免费获得正确的算法。
我猜你的架构包含类似下面的表格:
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
作为一方好处,你可以使用相同的查询来过滤驱动程序,日期等。
这些是表中唯一的列吗? – scsimon
对不起,他们不是。试图保持尽可能简单,但也有其他领域,如到达/离开日期/时间,卡车号码,司机代码等。 – CBode
我正在寻找一个目的地和起源的ID字段,但没有什么大不了 – scsimon