选择组中的最小值

时间:2013-03-16 01:06:14

标签: sql sql-server sql-server-2008 sql-server-2012

我有一张桌子

ID,  name, pay1, pay2
 1     a,    3,    2
 2     b,   12,    4
 3     b,    4,    8
 4     c,    8,    7
 5     c,    5,    2
 6     a,    7,    1

我想为每个名字选择pay1 + pay2最小的行。所以,我想得到

 ID,  name, pay1, pay2
 1     a,    3,    2
 3     b,    4,    8
 5     c,    5,    2

知道如何在SQL Server中这样做吗?感谢

3 个答案:

答案 0 :(得分:5)

使用排名功能:

with minpay as
(
  select *
    , payrank = row_number() over (partition by name order by pay1 + pay2, ID)
  from pay
)
select ID
  , name
  , pay1
  , pay2
from minpay
where payrank = 1
order by name

SQL Fiddle with demo

答案 1 :(得分:3)

OP没有提到如何处理可能的关系,但是:

select t1.* 
from table1 t1 join
(select id, sum(pay1 + pay2) as sumpay 
from table1  
group by id) s on t1.id = s.id
join 
(select name, min(pay1 + pay2) as sumpay 
from table1 
group by name) t on t.sumpay = s.sumpay 

我发布了这个,然后看到伊恩的答案更清楚了。

SQLFiddle with Demo.

答案 2 :(得分:0)

这是另一种选择。

这个将显示最小值的关系。 正如@MitchWheat指出的那样,问题没有具体说明如何处理这些问题。

SELECT a.Id, a.Name, a.Pay1, a.Pay2
FROM [table] a INNER JOIN (
    SELECT Name, MIN(Pay1 + Pay2) as MinPay
    FROM [table]
    GROUP BY Name
) b ON a.Name = b.Name
    AND a.Pay1 + a.Pay2 = b.MinPay