获得最高记录价值

时间:2017-10-24 05:44:36

标签: sql sql-server-2008

我有以下查询,它返回与之关联的所有严重性级别的样本。

但我只需要一个严重程度来挑选最高等级。

我尝试了什么

select S.sampleCode,asd.severityLevelRank
from prod.Samples S
left outer join prod.SampleFractions sf on sf.sampleId=S.sampleId
left outer join prod.LabRepetitions lr on 
sf.sampleFractionId=lr.sampleFractionId
left outer join prod.LabRepetitionResults lrr on 
lrr.labRepetitionId=lr.labRepetitionId
left outer join prod.AssessmentDataChecks asd on 
lrr.labRepetitionResultId=asd.labRepetitionResultId

group by S.sampleCode, asd.severityLevelRank

order by S.sampleCode desc, asd.severityLevelRank desc

我得到了什么

enter image description here

但我需要一个排名最高的样本3。

3 个答案:

答案 0 :(得分:1)

如果您希望每组样本的排名最高,则可以尝试使用DENSE_RANK()。请注意,在此处使用密集排名非常有用,因为它可以减轻您在GROUP BY聚合期间删除的重复样本/严重性记录的担忧。如果给定样本出现重复的严重性等级,则等级不会增加。

SELECT
    sampleCode,
    severityLevelRank
FROM
(
    SELECT
        S.sampleCode, asd.severityLevelRank,
        DENSE_RANK() OVER (PARTITION BY S.sampleCode ORDER BY asd.severityLevelRank) dr
    FROM prod.Samples S
    LEFT JOIN prod.SampleFractions sf
        ON sf.sampleId = S.sampleId
    LEFT JOIN prod.LabRepetitions lr
        ON sf.sampleFractionId = lr.sampleFractionId
    LEFT JOIN prod.LabRepetitionResults lrr
        ON lrr.labRepetitionId = lr.labRepetitionId
    LEFT JOIN prod.AssessmentDataChecks asd
        ON lrr.labRepetitionResultId = asd.labRepetitionResultId
) t
WHERE
    dr = 1
ORDER BY
    sampleCode DESC,
    severityLevelRank DESC

答案 1 :(得分:1)

只需替换

select S.sampleCode,asd.severityLevelRank

通过

select S.sampleCode, MAX(asd.severityLevelRank)

在SELECT。

您也可以添加

WHERE asd.severityLevelRank IS NOT NULL 

在FROM

忽略具有空值的sampleCode。

答案 2 :(得分:1)

除非我遗漏了某些内容,否则group by只有max

select S.sampleCode, max(asd.severityLevelRank) As severityLevelRank
from prod.Samples S
left outer join prod.SampleFractions sf on sf.sampleId=S.sampleId
left outer join prod.LabRepetitions lr on 
sf.sampleFractionId=lr.sampleFractionId
left outer join prod.LabRepetitionResults lrr on 
lrr.labRepetitionId=lr.labRepetitionId
left outer join prod.AssessmentDataChecks asd on 
lrr.labRepetitionResultId=asd.labRepetitionResultId

group by S.sampleCode

order by S.sampleCode desc