2014-03-31 52 views
0

連續數據我有一個SQL表以下數據:
I have the following data in a SQL Table:
我想找到沒有與ID 3點連續的數據組。結果是如何找到在SQL

Result
如何編寫query.please幫助。

+0

你受限於只使用SQL,或者你從另一種語言查詢? – austin1howard

+0

爲什麼選擇行(6,a1,1),(3,a2,5)和(5,a3,4)?他們沒有第二和第三個連續的行 –

+0

因此,對於任何特定的「ID」值,您要選擇具有最低「否」值且在「否」中連續的3行(因此,「Qty」我們選擇的行沒有作用)? –

回答

1

這裏是查詢其只選擇這裏居然連續3行是行:

SELECT a.* 
FROM 
TABLE as a 
inner join 
TABLE as b on (a.no+1=b.no and a.id=b.id) 
inner join 
TABLE as c on (a.no+2=c.no and a.id=c.id) 
order by a.id, a.no 

爲您的數據將提供:

4 a1 4 
5 a1 3 
1 a2 2 
2 a2 4 
3 a3 2 
4 a3 3 

行(6,A1,1),(3 ,a2,5),(5,a3,4)沒有被選擇,因爲沒有(8,A1)(5,a2)和(7,A3)

+0

對我來說感謝幫助,但是這個查詢不好我的問題。 –

0
DECLARE @temp TABLE (NO int,ID VARCHAR(2),QTY int) 
INSERT INTO @temp 
SELECT 1,'A1',5 UNION ALL 
SELECT 4,'A1',4 UNION ALL 
SELECT 5,'A1',3 UNION ALL 
SELECT 6,'A1',1 UNION ALL 
SELECT 7,'A1',0 UNION ALL 
SELECT 9,'A1',5 UNION ALL 
SELECT 12,'A1',3 UNION ALL 
SELECT 1,'A2',2 UNION ALL 
SELECT 2,'A2',4 UNION ALL 
SELECT 3,'A2',5 UNION ALL 
SELECT 4,'A2',1 UNION ALL 
SELECT 7,'A2',4 UNION ALL 
SELECT 9,'A2',5 UNION ALL 
SELECT 1,'A3',0 UNION ALL 
SELECT 3,'A3',2 UNION ALL 
SELECT 4,'A3',3 UNION ALL 
SELECT 5,'A3',4 UNION ALL 
SELECT 6,'A3',2; 

WITH tmpa AS 
(
    SELECT * 
     , NO - ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) AS grp 
    FROM @temp 
) 
, tmpb AS 
(
    SELECT * 
     , COUNT(*) OVER(PARTITION BY ID,grp) AS grpcount 
    FROM tmpa 
) 
SELECT NO,ID,QTY FROM tmpb WHERE grpcount>1; 

結果是

4 A1 4 
5 A1 3 
6 A1 1 
7 A1 0 
1 A2 2 
2 A2 4 
3 A2 5 
4 A2 1 
3 A3 2 
4 A3 3 
5 A3 4 
6 A3 2 

我從此鏈接中找到此查詢。 Find 「n」 consecutive free numbers from table

http://sqlfiddle.com/#!1/a2633/2

Answer Credit by

+0

唯一的問題是......它給出了你預期的不同結果 –