SQL Server查询以选择本地最大值

时间:2010-02-01 18:33:41

标签: sql greatest-n-per-group

我有这些数据。我需要为每个人获得最低的$ full行。

Amount Date    Name
$123   Jun 1   Peter
$120   Jun 5   Peter
$123   Jun 5   Paul
$100   Jun 1   Paul
$220   Jun 3   Paul

SQl Server查询的结果应为:

$120   Jun 5   Peter
$100   Jun 1   Paul

5 个答案:

答案 0 :(得分:3)

SQL Server 2005+版本

;WITH CTE AS
(
    SELECT
        Amount, [Date], Name,
        ROW_NUMBER() OVER (PARTITION BY Name ORDER BY [Amount]) AS RowNum
    FROM Table
)
SELECT *
FROM CTE
WHERE RowNum = 1

替代版本

SELECT t.Amount, t.[Date], t.Name
FROM
(
    SELECT Name, MIN(Amount) AS MinAmount
    FROM Table
    GROUP BY Name
) m
INNER JOIN Table t
    ON t.Name = m.Name
    AND t.Amount = m.Amount

答案 1 :(得分:2)

适用于SQL Server 7及更高版本的一种方法

select t1.* 
from(select min(amount) Minamount,name
from Yourtable
group by name) t2 
join Yourtable t1 on t1.name = t2.name
and t1.amount = t2.Minamount

有几种方法可以解决此问题,请参阅此处:Including an Aggregated Column's Related Values

答案 2 :(得分:1)

SELECT * FROM TableName T1 WHERE NOT EXISTS 
    (SELECT * FROM TableName T2 
    WHERE T2.Name = T1.Name AND T2.Amount < T1.Amount)

如果发生关系,这两个行都将在此方案中显示。

答案 3 :(得分:1)

将人员分组以获得每个人的最低金额,然后加入表格以获取每一行的日期:

select y.Amount, y.Date, y.Name
from (
  select min(Amount), Name
  from TheTable
  group by Name
) x
inner join TheTable y on x.Name = y.Name and x.Amount = y.Amount

如果金额可以存在于一个人的多个日期,请选择其中一个日期,例如第一个:

select y.Amount, min(y.Date), y.Name
from (
  select min(Amount), Name
  from TheTable
  group by Name
) x
inner join TheTable y on x.Name = y.Name and x.Amount = y.Amount
group by y.Amount, y.Name

答案 4 :(得分:1)

不是最有效的,但更容易阅读:

SELECT DISTINCT [Name], [Date], MIN([Amount]) OVER(PARTITION BY [Name])
FROM #Table