2011-06-27 98 views
0

我已經得到了郵件存儲 這樣一個表中的一行: codMsg,消息,anotherCod選擇每個代碼

1, 'hi', 1 
2, 'hello', 1 
3, 'wasup', 1 
4, 'yo', 2 
5, 'yeah', 2 
6, 'gogogo', 3 

我在想,如果可以選擇每個anotherCod

的頂部1

我想到:

1, 'hi', 1 
4, 'yo', 2 
6, 'gogogo', 3 

我想整條生產線,而不僅僅是anotherCod的數量,所以按不應該工作

回答

1
select mytable.* 
from mytable 
join (select min(codMsg) as codMsg, anotherCod from mytable group by 2) x  
    on mytable.codMsg = x.codMsg 
0
SELECT 
    * 
FROM 
    myTable 
WHERE 
    codMSG = (SELECT MIN(codMsg) FROM myTable AS lookup WHERE anotherCod = myTable.anotherCod) 
1

的SQL Server 2005+,甲骨文:

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 
+1

+1:如果窗的功能提供給你,我肯定會走這條路。請注意,如果綁定在ORDER BY中,則RANK()*可以給多個行賦予相同的值,其中ROW_NUMBER()將隨機地將它們排序到不同的位置。 – MatBailie