2009-09-29 84 views
3

如果我有如下表:SQL語句(S)

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中

+0

+1爲表創建和插入語句。但是,如果我正確地理解了這個問題,它就會出現,應該返回給定測試數據中的所有行。我會建議包含將被正確查詢排除的行。 – 2009-09-29 02:31:57

回答

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; 
+0

這就是它,但在子查詢中有一個額外的')',並且該數字需要在一個組中。 (不能編輯) – SBurris 2009-09-29 01:24:41

+0

是的,我希望你可以在StackOverflow上運行正確的東西... – 2009-09-29 02:21:02

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; 
1

您使用SQL Server 2005中,所以它的價值至少在探索over條款:

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

我想獲得一個表顯示每個問題的三個最新版本

  1. I 假定該qversion隨時間增加。如果此假設倒退,請從答案中刪除desc關鍵字。
  2. 表定義在qversion上沒有顯式非空約束。 I 假定應該排除空qversion。 (注意:根據設置,聲明中缺少顯式的null/not null可能會導致非null約束。)如果表的確有非空的約束,則應刪除文本where qversion is not null。如果qversion可以爲null,並且需要將null包含在結果集中,則需要進行其他更改。

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