![](/img/trans.png)
[英]How to SELECT rows with MIN(DateTime column), GROUP by another column and DISTINCT by another column in SQL?
[英]Select min group by another column
我有包含以下字段的表:
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
谢谢
您可以在大多数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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.