Question

I have a SQL query I am trying to write but haven't been able to come up with the solution.

2 entries in my table that are related, are related through the first 3 characters of the ID. When a new item is added that needs to be related to a certain entry, the first 3 characters are added, and then the 2nd two are incremented by one to create the new ID. When a completely sepere entry is needed a unique 3 digit string is used and starts the second two chars with "00". There may be some that have large gaps in the last 2 columns because of deleted data (I don't want these in my query)

What I would like to do is get only the rows where there is another row with the same first 3 characters and 1 less from the count of the last 2.

Table Example:

ID    |  Date 
====== ========
11100 | 07/12
22211 | 07/13
12300 | 07/14
11101 | 07/14
11400 | 07/16
22212 | 07/16

The Query should only return these elements because there exsists another entry with the same first 3 chars and one less from the last 2 chars .

ID    |  Date 
====== ========
11101 | 07/14
22212 | 07/16
Was it helpful?

Solution

Looks like a simple JOIN will do it;

SELECT a.*
FROM Table1 a
JOIN Table1 b
  ON a.id/100 = b.id/100
 AND a.id = b.id + 1

An SQLfiddle to test with.

You can also write it as an EXISTS query;

SELECT a.* 
FROM Table1 a
WHERE EXISTS (
  SELECT 1 FROM Table1 b WHERE b.id = a.id-1
     AND a.id/100 = b.id/100
)

Another SQLfiddle.

OTHER TIPS

Declare @a table(ID Varchar(10),  [Date] varchar(10))
Insert into @a
Select '11100','07/12'
UNION  Select '22211','07/13'
UNION  Select '12300','07/14'
UNION  Select '11101','07/14'
UNION  Select '11400','07/16'
UNION  Select '22212','07/16'

Select a.* from
@a a
JOIN
(
Select SubString(ID,1,3) + RIGHT('0'+Cast(MAX(Cast(SubString(ID,4,2) as int)) as Varchar(10)),2) as ID
from @a
group by SubString(ID,1,3)
Having Count(*)>1
) x
on x.ID=a.ID

Try this

SELECT T1.ID,T1.[Date] FROM Table1 T1 INNER JOIN  
(
  SELECT LEFT(ID,3) AS ID,MAX([Date]) AS [Date] FROM Table1
  GROUP BY LEFT(ID,3)
  HAVING COUNT(LEFT(ID,3)) > 1
) T2 ON LEFT(T1.ID,3) = T2.ID
AND T1.[Date] = T2.[Date]

SQL FIDDLE DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top