从表中选择不同的前4条记录

时间:2013-03-14 23:42:25

标签: sql sql-server

我有以下SQL Server表

我想要从下表中获取最新的所有前4个不同代码 请记住,我希望返回所有列,而不仅仅是代码列。

sno  city      state  country  code  date
1    new york  NY      US      1234  1/1/2013
2    Houston   TX      US      2234  1/6/2013 
3    LA        CA      US      1123  1/2/2013
4    Chicago   IL      US      1244  1/3/2013
5    Brooklyn  NY      US      1234  1/4/2013
6    Dallas    TX      US      2234  1/5/2013

我的以下选择查询返回重复的代码,但我想要不同的最新代码。

select top 4 * from table1 where code in (select distinct code from table1) 

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:8)

WITH topList
AS
(
    SELECT  sno, city, state, country, code, date,
            ROW_NUMBER() OVER(PARTITION BY code ORDER BY DATE DESC) rn
    FROM    TableName
)
SELECT  TOP 4 sno, city, state, country, code, date
FROM    topList
WHERE   rn = 1
ORDER   BY DATE DESC

输出

╔═════╦══════════╦═══════╦═════════╦══════╦════════════╗
║ SNO ║   CITY   ║ STATE ║ COUNTRY ║ CODE ║    DATE    ║
╠═════╬══════════╬═══════╬═════════╬══════╬════════════╣
║   2 ║ Houston  ║ TX    ║ US      ║ 2234 ║ 1/6/2013   ║
║   5 ║ Brooklyn ║ NY    ║ US      ║ 1234 ║ 1/4/2013   ║
║   4 ║ Chicago  ║ IL    ║ US      ║ 1244 ║ 1/3/2013   ║
║   3 ║ LA       ║ CA    ║ US      ║ 1123 ║ 1/2/2013   ║
╚═════╩══════════╩═══════╩═════════╩══════╩════════════╝

答案 1 :(得分:2)

GROUP BY

相当简单
SELECT TOP 4 * FROM table1
WHERE sno IN (SELECT MAX(sno) FROM table1 GROUP BY code)
ORDER BY date DESC;

尽管如此,这是sno的最新(?)组,而非日期。