SQL语句

时间:2009-09-29 00:44:02

标签: sql sql-server sql-server-2005 tsql greatest-n-per-group

如果我有下表:

CREATE TABLE #temp (
    id int,
    num int,
    question varchar(50),
    qversion int );

INSERT INTO #temp VALUES(1, 1, 'Question 1 v1', 1);
INSERT INTO #temp VALUES(2, 1, 'Question 1 v2', 2);
INSERT INTO #temp VALUES(3, 2, 'Question 2 v1', 1);
INSERT INTO #temp VALUES(4, 2, 'Question 2 v2', 2);
INSERT INTO #temp VALUES(5, 2, 'Question 2 v3', 3);
INSERT INTO #temp VALUES(6, 3, 'Question 3 v1', 1);

SELECT *
FROM #temp;

DROP TABLE #temp;

我想找一张桌子来展示他们最新版本中的三个问题?这是在SQL Server 2005

4 个答案:

答案 0 :(得分:3)

CREATE TABLE #temp (
    id int,
    num int,
    question varchar(50),
    qversion int );

INSERT INTO #temp VALUES(1, 1, 'Question 1 v1', 1);
INSERT INTO #temp VALUES(2, 1, 'Question 1 v2', 2);
INSERT INTO #temp VALUES(3, 2, 'Question 2 v1', 1);
INSERT INTO #temp VALUES(4, 2, 'Question 2 v2', 2);
INSERT INTO #temp VALUES(5, 2, 'Question 2 v3', 3);
INSERT INTO #temp VALUES(6, 3, 'Question 3 v1', 1);

WITH latest AS (
   SELECT num, MAX(qversion) AS qversion
   FROM #temp
   GROUP BY num
)
SELECT #temp.*
FROM #temp
INNER JOIN latest
    ON latest.num = #temp.num
    AND latest.qversion = #temp.qversion;

DROP TABLE #temp;

答案 1 :(得分:1)

SELECT t1.id, t1.num, t1.question, t1.qversion
FROM #temp t1
LEFT OUTER JOIN #temp t2
  ON (t1.num = t2.num AND t1.qversion < t2.qversion)
GROUP BY t1.id, t1.num, t1.question, t1.qversion
HAVING COUNT(*) < 3;

答案 2 :(得分:1)

您正在使用SQL Server 2005,因此至少可以探索over子句:

select
    *
from
    (select *, max(qversion) over (partition by num) as maxVersion from #temp) s
where
    s.qversion = s.maxVersion

答案 3 :(得分:1)

我想找个表来显示每个问题的三个最新版本

  1. 假设该qversion随着时间的推移而增加。如果此假设是向后的,请从答案中删除desc关键字。
  2. 表定义在qversion上没有明确的not null约束。我假设应排除零qversion。 (注意:根据设置,声明中缺少显式的null / not null可能会导致非null约束。)如果表的确具有非空约束,则应删除文本where qversion is not null。如果qversion可以为null,并且需要在结果集中包含空值,则需要进行其他更改。

  3. CREATE TABLE #temp (
        id int,
        num int,
        question varchar(50),
        qversion int );
    
    INSERT INTO #temp VALUES(1, 1, 'Question 1 v1', 1);
    INSERT INTO #temp VALUES(2, 1, 'Question 1 v2', 2);
    INSERT INTO #temp VALUES(3, 2, 'Question 2 v1', 1);
    INSERT INTO #temp VALUES(4, 2, 'Question 2 v2', 2);
    INSERT INTO #temp VALUES(5, 2, 'Question 2 v3', 3);
    INSERT INTO #temp VALUES(7, 2, 'Question 2 v4', 4); 
    -- ^^ Added so at least one row would be excluded.
    INSERT INTO #temp VALUES(6, 3, 'Question 3 v1', 1);
    INSERT INTO #temp VALUES(8, 4, 'Question 4 v?', null);
    
    select id, num, question, qversion
    from (select *, 
            row_number() over (partition by num order by qversion desc) as RN
        from #temp
        where qversion is not null) T
    where RN <= 3