返回具有最小值的列的行

时间:2014-06-17 18:59:25

标签: sql sql-server reporting-services ssrs-2008

我有一个场景

Key Name Amt
101 Nikh 100
101 Mark 150
101 Jess 75
102 Sam  200
102 Lee  150

观察多个记录的密钥相同。它也来自与Name和Amt不同的表格。我想要返回记录havig最低Amt。以下是例如:

Key  Name  Amt
101  Jess  75
102  Lee   150

到目前为止,我运行的代码返回Key和Amt记录,如何添加Name列并确保它返回与min(Amt)关联的名称 Pl注意:我正在研究SSRS 2008。

为了更好地理解,我在这里粘贴我的代码(编辑):

SELECT       A.AppID,A.AppDetailID, MIN(B.Amt) AS LOWAmt
FROM         AppDetail AS A 
LEFT OUTER JOIN
(SELECT        TOP (100) PERCENT C.AppID, C.PartyID, MIN(C.TotalScore) AS Amt, D.Name, D.Indicator, E.FirstName, E.LastName
     FROM       DetailGuarantor AS D RIGHT OUTER JOIN
     Applicant AS E ON D.BeginDate = E.BeginDate AND 
     D.PartyID = E.PartyID AND 
     D.AppID = E.AppID RIGHT OUTER JOIN
     ApplicationScore AS C ON 
     E.AppID = C.AppID AND 
     E.PartyID = C.PartyID
     GROUP BY C.AppID, C.PartyID, D.Name, D.Indicator, E.FirstName, E.LastName, 
     ORDER BY C.AppID, Amt) AS B ON A.AppID = B.AppID 

GROUP BY A.AppID,A.AppDetailID

3 个答案:

答案 0 :(得分:3)

经典问答

;WITH CTE as
(
  SELECT row_number() over (partition by  [Key] order by Amt) rn, 
    [Key],
    Name,
    Amt
  FROM <table>
)
SELECT [Key], Name, Amt
FROM CTE
WHERE rn = 1

修改:如果是关系,您希望显示所有具有最低Amt的结果,请将row_number()替换为rank()

答案 1 :(得分:2)

您应该使用row_number()

来解决此问题
select [key], name, amt
from (select t.*, row_number() over (partition by [key] order by amt asc) as seqnum
      from table t
     ) t
where seqnum = 1;

答案 2 :(得分:0)

如果您只想要一个简单的查询,那么这是一种方法:

SELECT       Tab.KeyID, Tab.Name, Tab.Amt
FROM         Tab
INNER JOIN  (SELECT     MIN(Amt) as 'minAmt', [KeyID]
             FROM       Tab
             GROUP BY   [KeyID]) lowestAmt

ON           Tab.KeyID = lowestAmt.KeyID

WHERE        Tab.Amt = lowestAmt.minAmt
GROUP BY     Tab.KeyID, Tab.Name, Tab.Amt
ORDER BY     Tab.KeyID

你可以在这里看到 - &gt; http://sqlfiddle.com/#!3/b2628/39

希望这有帮助!!!