嗨我在获取查询中有一个问题,比如3列
ID Grp Name
1 10 aa
2 11 bb
3 11 cc
4 11 dd
5 12 ee
6 12 ff
我想要的是
ID Grp Name
1 10 aa
2 11 bb
5 12 ee
那么可以做什么?
答案 0 :(得分:2)
在sql server
中试试这个!
select * from
(
select *,rn=row_number()over(partition by Grp order by ID) from table
)x
where x.rn=1
答案 1 :(得分:1)
对于 SQL Server:
WITH CTE AS (SELECT *,RN=ROW_NUMBER() OVER(PARTITION BY Grp ORDER BY ID)
FROM TableName)
SELECT ID,Grp,Name
FROM CTE
WHERE RN=1
SQL Fiddle中的示例。
对于 MySQL:
SELECT ID,Grp,Name
FROM
(SELECT A.ID, A.Grp, A.Name, count(*) as row_number FROM TableName A
JOIN TableName B ON A.Grp = B.Grp AND A.ID >= B.ID
GROUP BY A.Grp, A.ID,A.Name) T
WHERE row_number=1
SQL Fiddle中的示例。