如何使用sql选择最新年份的记录

时间:2013-05-23 09:44:29

标签: sql sql-server

我正在使用SQL Server。我想列出教程的每周信息。

SELECT 
       tx.Lab, t.weekNo 
FROM 
       TutorialX tx 
INNER JOIN 
       Tutorial t 
ON 
       tx.id = t.id 
WHERE 
       t.tutID = @tutID AND 
       t.ProgramID = @pID AND 
       tx.Culture = @culture      
ORDER BY 
       t.WeekNo

年份字段位于表格Tutorial

此查询为我提供了所有年份的记录。每年有14~16条记录。每年将有14到16个新记录,但我想只获得最大/最新年份的记录。今天,我希望获得2012年的14到16个记录,明年是2013年......

我试过这个但是使用这个查询的结果是一样的:

SELECT 
       tx.Lab, t.weekNo 
FROM 
       TutorialX tx 
INNER JOIN 
       Tutorial t 
ON 
       tx.id = t.id 
WHERE 
       t.tutID = @tutID AND 
       t.ProgramID = @pID AND 
       tx.Culture = @culture AND
       t.year IN ( SELECT MAX(year) AS y FROM Tutorial GROUP BY year)
ORDER BY 
       t.WeekNo

2 个答案:

答案 0 :(得分:1)

如果您使用的是SQL Server 2005+,则可以使用ranking function ROW_NUMBER() OVER(PARTITION BY ...)执行此操作:

WITH CTE
AS
(
    SELECT  tx.Lab,
      ROW_NUMBER() OVER(PARTITION BY year ORDER BY t.weekno) AS RN 
    FROM TutorialX tx 
    INNER JOIN Tutorial t ON tx.id = t.id 
    WHERE t.tutID = @tutID 
      AND t.ProgramID = @pID 
      AND tx.Culture = @culture      
)
SELECT Lab
FROM CTE
WHERE RN = 1;

答案 1 :(得分:0)

我已解决了在内部查询中删除GROUP BY year部分的问题。

SELECT 
    t.weekNo, tx.Lab 
FROM 
    TutorialX tx 
INNER JOIN 
    Tutorial t 
ON 
    tx.id = t.id 
WHERE 
    t.tutID = @tid AND 
    t.ProgramID = @pid AND 
    tx.Culture = @culture AND 
    t.year IN (SELECT MAX(year) AS y FROM Tutorial) 
ORDER BY 
    t.weekNo