Select one line of each code
I've got a Table that stores messages like this: codMsg, message, anotherCod
1, 'hi', 1
2, 'hello', 1
3, 'wasup', 1
4, 'yo', 2
5, 'yeah', 2
6, 'gogogo', 3
I was wondering if is possible to select top 1 of each anotherCod
Wh开发者_运维知识库at I expect:
1, 'hi', 1
4, 'yo', 2
6, 'gogogo', 3
I want the whole line, not just the number of the anotherCod, so group by should not work
select mytable.*
from mytable
join (select min(codMsg) as codMsg, anotherCod from mytable group by 2) x
on mytable.codMsg = x.codMsg
SQL Server 2005+, Oracle :
SELECT codMsg,
message,
anotherCod
FROM
(
SELECT codMsg,
message,
anotherCod,
RANK() OVER (PARTITION BY anotherCod ORDER BY codMsg ASC) AS Rank
FROM mytable
) tmp
WHERE Rank = 1
SELECT
*
FROM
myTable
WHERE
codMSG = (SELECT MIN(codMsg) FROM myTable AS lookup WHERE anotherCod = myTable.anotherCod)
精彩评论