简体   繁体   English

Access SQL-根据多列中的条件返回唯一行

[英]Access SQL - Return unique rows based on criteria in multiple columns

I have two tables of zipcodes containing drivetime data. 我有两个包含行驶时间数据的邮政编码表。 The first (called "DTM") contains 4 columns. 第一个(称为“ DTM”)包含4列。 The first two columns are From and To zipcodes, followed by drivetime and driving distance between them. 前两列是“从”和“到”邮政编码,然后是行驶时间和它们之间的行驶距离。 This table contains every combination of zipcodes twice, with From and To zips reversed. 该表包含两次邮政编码的每种组合,其中“从”和“到”邮政编码颠倒了。 it looks something like this: 它看起来像这样:

FROM_ZIP  TO_Zip  Drivetime(min)  Distance(mtr)
1011      1011    0                0
1011      1012    3                650
1011      1013    4                850
1011      1014    4                900
1012      1011    3                650
1012      1012    0                0 
1012      1013    2                500
...

This table contains roughly 16.5 million records. 该表包含大约1,650万条记录。
The second table (called "STOREZIPS") contains a list of zipcodes belonging to stores. 第二个表(称为“ STOREZIPS”)包含属于商店的邮政编码列表。

My goal here is to match every zipcode in the country to the zipcode of the store that is closest by, and show the drivetime and driving distance. 我的目标是使该国家/地区中的每个邮政编码与附近的商店的邮政编码匹配,并显示行车时间和行车距离。 So what i'm trying to do is extract from the first table the rows in which the TO_Zip matches one of the zipcodes in the second table, and have the lowest Drivetime(min) . 所以我想做的是从第一张表中提取TO_Zip与第二张表中的一个TO_Zip匹配的行,并且具有最低的Drivetime(min)

There are however also instances where two Zip's have the same Drivetime(min) to another Zip. 但是,在某些情况下,两个Zip与另一个Zip具有相同的行驶时间Drivetime(min) If this occurs the row with the lowest Distance(mtr) should be selected. 如果发生这种情况,应选择Distance(mtr)最低的行。

I've been trying to solve this for a while now, but just can't seem to get it in such a way that only the From_Zip that is closest by gets selected. 我已经尝试解决了一段时间,但似乎无法以仅选择最接近的From_Zip的方式来From_Zip

Any help or suggestion is appreciated. 任何帮助或建议,表示赞赏。

I think that you will need to use CTE in that case. 我认为在这种情况下,您将需要使用CTE。 You can read more here: https://technet.microsoft.com/en-us/library/ms190766(v=sql.105).aspx 您可以在此处阅读更多信息: https : //technet.microsoft.com/zh-cn/library/ms190766(v=sql.105).aspx

If I understood you well I think that sample sql may look like this: 如果我对您的了解很好,我认为示例sql可能看起来像这样:

with cte as 
(
    select min(c.Drivetime) as minimum, c.zipT, 
    c.Distance, rank() over (partition by c.TO_Zip order by   c.Distance) as place      
    from DTM c
    inner join STOREZIPS s on c.TO_Zip = s.TO_Zip
    where c.Drivetime > 0
    group by c.TO_Zip, c.Distance   
 ) select * from cte where place = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM