0

I have the following data in a SQL Table:
I have the following data in a SQL Table:
I want to find 3 Consecutive data by No and group with ID. Result are

Result
How to write query.please help.

Paing Hein Thu
  • 115
  • 1
  • 1
  • 10
  • Are you constrained to using only SQL, or are you querying from another language? – austin1howard Mar 31 '14 at 06:18
  • Why rows (6,a1,1), (3,a2,5) and (5,a3,4) are selected? they don't have 2nd and 3rd consecutive rows – Iłya Bursov Mar 31 '14 at 06:29
  • So, for any particular `ID` value, you want to select the 3 rows which have the lowest `No` values and are consecutive in `No` (so, `Qty` plays no role in which rows we select)? – Damien_The_Unbeliever Mar 31 '14 at 06:29
  • most prefer SQL but also using C#. – Paing Hein Thu Mar 31 '14 at 06:58
  • @Damien_The_Unbeliever `Qty` field are checking only example: I want to `Qty >=0 and Qty<=5` and consecutive going 3 times. so (4,A1,4),(5,A1,3),(6,A1,1),(7,A1,0) are consecutive but I want to 3 consecutive so (4,5,6) `No` field are consecutive for `A1` data – Paing Hein Thu Mar 31 '14 at 07:22

2 Answers2

1

Here is query which select only rows where actually 3 consecutive rows are:

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

for your data it will provide:

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

rows (6,a1,1), (3,a2,5) and (5,a3,4) are not selected, as there are no (8,a1) (5,a2) and (7,a3)

Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
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;

Result are

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

I found this query from this link. Find “n” consecutive free numbers from table

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

Answer Credit by

Community
  • 1
  • 1
Paing Hein Thu
  • 115
  • 1
  • 1
  • 10