Author |
Topic |
ashley.sql
Constraint Violating Yak Guru
299 Posts |
Posted - 2009-08-31 : 16:43:45
|
declare @test table(prodid int, serialno int)insert into @test select 1, 2220 union allSELECT 1, 2221 UNION ALLSELECT 1, 2222 UNION ALLSELECT 1, 2223 UNION ALLSELECT 1, 2224 UNION ALLSELECT 1, 3331 UNION ALLSELECT 1, 3332 UNION ALLSELECT 1, 3333 UNION ALLSELECT 2, 4442 UNION ALLSELECT 2, 4443 UNION ALLSELECT 2, 4444 UNION ALLSELECT 2, 4445 UNION ALLSELECT 2, 4446 UNION ALLSELECT 2, 8776 UNION ALLSELECT 2, 8777 UNION ALLSELECT 3, 9995 UNION ALLSELECT 3, 9996 UNION ALLSELECT 3, 9997 UNION ALLSELECT 3, 445 UNION ALLSELECT 3, 446 UNION ALLSELECT 3, 447 SELECT * FROM @TESTProdID, SerialNoFrom, SerialNoTo1 2220 22241 3331 33332 4442 44462 8776 87773 9995 99973 445 447 so in the serialnofrom we should have Minimum serial number and in serialnoto we should have maximum, but only for the serial numberswhich are consective and have a difference of 1. as soon as the series breaks a new row should be created and have the new minimum serial number and maximum serial number.-----------------------------------------------------------------------------------------------Ashley Rhodes |
|
Nageswar9
Aged Yak Warrior
600 Posts |
Posted - 2009-09-01 : 00:18:22
|
Hi, Try this onceSELECT PRODID,MIN(SERIALNO) AS SerialNoFrom, MAX(SERIALNO) AS SerialNoTo FROM ( SELECT PRODID, ROW_NUMBER() OVER ( PARTITION BY LEFT(SERIALNO,2),LEN(SERIALNO) ORDER BY SERIALNO ) AS RID, SERIALNO FROM @TEST ) TGROUP BY LEFT(SERIALNO,2),LEN(SERIALNO),PRODIDORDER BY PRODID |
|
|
ra.shinde
Posting Yak Master
103 Posts |
Posted - 2009-09-01 : 03:19:15
|
If I add SELECT 1, 2298 UNION ALLSELECT 1, 2299 UNION ALLSELECT 1, 2300 UNION ALLthese records to above data,Then above query is giving result as 1, 2220, 22991, 2300, 23001, 3331, 33332, 4442, 44462, 8776, 87773, 445, 4473, 9995, 9997.which is not as expectedRahul Shinde |
|
|
ra.shinde
Posting Yak Master
103 Posts |
Posted - 2009-09-01 : 03:52:02
|
SELECT PRODID, MIN(SERIALNO) AS MINSNO, MAX(SERIALNO) AS MAXSNOFROM(SELECT (ROW_NUMBER() OVER (ORDER BY PRODID, SERIALNO)+1)/2 AS RN, PRODID, SERIALNOFROM(SELECT * FROM @TEST WHERE SERIALNO NOT IN ( SELECT SERIALNO + 1 FROM @TEST)UNION SELECT * FROM @TEST WHERE SERIALNO NOT IN ( SELECT SERIALNO - 1 FROM @TEST)) T) TB GROUP BY PRODID, RNRahul Shinde |
|
|
|
|
|