按另一列选择最小组

时间:2015-06-19 08:23:14

标签: sql sql-server min

我的表包含以下字段:

id  |   GroupId | position      
 ------------------------------------
 CK1         10       1
 CK1         10       2    
 CK1         10       3    
 CK1         11       4    
 CK1         11       5    
 CK1         11       6    
 CK1         12       7    
 CK1         12       8    
 CK1         12       9 

我需要一个包含注册组中位置最小值的选择:

id  |   GroupId | position   | MinPosition         
 -------------------------------------------
 CK1         10       1             1
 CK1         10       2             1    
 CK1         10       3             1    
 CK1         11       4             4
 CK1         11       5             4
 CK1         11       6             4
 CK1         12       7             7
 CK1         12       8             7
 CK1         12       9             7

由于

2 个答案:

答案 0 :(得分:2)

您可以在大多数DBMS中使用它:

SELECT id, groupid, position, 
FROM myTable as mt
INNER JOIN (
        SELECT id, groupid, MIN(position)
        FROM myTable 
        GROUP BY id, groupid
    ) as mini
    ON mt.id = mini.id
    AND mt.groupid = mt.groupid

如果您使用SQL Server(> = 2008)

,这是更好的版本
SELECT id, groupid, position, MIN(position) OVER (PARTITION BY id, groupid)
FROM myTable as mt

这是一个完整的代码演示:

CREATE TABLE #temp(id char(3), groupid int, position int)

INSERT INTO #temp(id, groupid, position)
VALUES (N'CK1',10,1),(N'CK1',10,2),(N'CK1',10,3),(N'CK1',11,4),(N'CK1',11,5),(N'CK1',11,6),(N'CK1',12,7),(N'CK1',12,8),(N'CK1',12,9) 

SELECT id, groupid, position, MIN(position) OVER (PARTITION BY id, groupid)  as MinPosition
FROM #temp as mt

DROP TABLE #temp

这会产生这样的结果:

id   groupid     position    MinPosition
---- ----------- ----------- -----------
CK1  10          1           1
CK1  10          2           1
CK1  10          3           1
CK1  11          4           4
CK1  11          5           4
CK1  11          6           4
CK1  12          7           7
CK1  12          8           7
CK1  12          9           7

答案 1 :(得分:0)

declare @t table (id varchar(5),Groupid int)
insert into @t (id,Groupid)values ('CK1',10),
('CK1',10),
('CK1',10),
('CK1',11),
('CK1',11),
('CK1',11),
('CK1',12),
('CK1',12),
('CK1',12),
('CK1',12)

select id,Groupid,RANK()OVER( ORDER BY GROUPID)MINPosition
 from @t