我有一个存储消息的表 像这样: codMsg,message,anotherCod
1, 'hi', 1
2, 'hello', 1
3, 'wasup', 1
4, 'yo', 2
5, 'yeah', 2
6, 'gogogo', 3
我想知道是否有可能选择另一个的前1个
我的期望:
1, 'hi', 1
4, 'yo', 2
6, 'gogogo', 3
我想要整条线,而不仅仅是另一条线的数量,所以group by不应该工作
答案 0 :(得分:1)
select mytable.*
from mytable
join (select min(codMsg) as codMsg, anotherCod from mytable group by 2) x
on mytable.codMsg = x.codMsg
答案 1 :(得分:1)
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
答案 2 :(得分:0)
SELECT
*
FROM
myTable
WHERE
codMSG = (SELECT MIN(codMsg) FROM myTable AS lookup WHERE anotherCod = myTable.anotherCod)