根据列选择SQL中的记录

问题描述

我想根据在列中分配给它的“排名”来选择一条记录。例如,如果我有一个包含以下内容的表。

Sample | Site | Depth_From | Depth_To | Result | Ranking
111    |  AA  |  12        |    15    |  10    |  2
112    |  AA  |  12        |    13    |  8     |  1
113    |  AA  |  13        |    14    |  9     |  1
114    |  AA  |  14        |    15    |  11    |  1
115    |  BB  |  12        |    15    |  5     |  2

我想为每个深度间隔选择排名最高的样本,而不必重复读取。预期的结果将是这样。

Sample | Site | Depth_From | Depth_To | Result | Ranking
112    |  AA  |  12        |    13    |  8     |  1
113    |  AA  |  13        |    14    |  9     |  1
114    |  AA  |  14        |    15    |  11    |  1
115    |  BB  |  12        |    15    |  5     |  2

请注意,AA 12-15被忽略,因为在整个采样间隔内会有更高的“排名”结果,而BB 15-18则保留为“ 2”是该间隔内的最高“排名”。

我尝试将Site和Depth_From进行串联,然后根据排名进行大小写,但是目前还无法使其正常工作。

在此先感谢您的帮助。

解决方法

获取每个站点的唯一深度,然后使用交叉应用为排名最低的每个深度选择样本结果

select
    topRankSamples.*
from ( 
-- getting the unique depth intervals
select distinct Depth_From,Site
from someTable
) DepthInts
cross apply
(
    -- get the lowest ranked sample for each depth interval
    select top 1 Samples.Sample,Samples.Site,Samples.Result. Samples.Ranking
    from someTable as Samples
    where Samples.Depth_From = DepthInts.Depth_From and Samples.Site = DepthInts.Site
    order by Samples.Ranking asc
) topRankSamples