如果我有以下表:

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服务器2005年

有帮助吗?

解决方案

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;

其他提示

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;

您使用的是SQL Server 2005中,所以它的价值至少在探索 over 子句:

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

我想获得一个表格显示的三个最新版本中的每一个问题.

  1. 假设 那qversion是随着时间不断提高。如果这个假设是倒退,删除 desc 关键字从答复。
  2. 表中的定义没有明确not null约束qversion.我 假设 这一空qversion应排除在外。(注:根据设置,缺乏一个明确的null/not null在《宣言》可能导致不null约束。) 如果该表没有"not null"受约束,比文本 where qversion is not null 应该删除。如果qversion可以为空和空需要包括在结果设定的,那么其他更改将需要作出。

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top