0

我正在使用 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
4

2 回答 2

1

如果您使用的是 SQL Server 2005+,则可以使用排名功能 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;
于 2013-05-23T09:46:20.813 回答
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
于 2013-05-23T10:18:08.370 回答