Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Join/Where

Status
Not open for further replies.

earthandfire

Programmer
Mar 14, 2005
2,924
GB
I thought this was going to be straightforward, but I've tried every combination of Join and Where that I can think of and I'm beaten

Code:
...
...
...

DECLARE @clno int
DECLARE @chno	varchar(22)
DECLARE @repdt datetime

CREATE TABLE #currentclaims(claimno int)
INSERT INTO #currentclaims SELECT ClaimNo FROM ClaimsList

SET @Counter = ((SELECT Sum(DefaultCount) FROM AccountCodesDefault) + @BusCount) - (SELECT Count(*) FROM ClaimsList)
IF @Counter > 0
BEGIN
	SET @LocalCount = 1
	WHILE @LocalCount <= @Counter
	BEGIN
		SELECT TOP 1
			@clno = t.ClaimNo, @chno = t.ChassisNo, @repdt = t.RepairDate
		FROM
			#tmpTrucks t JOIN ClaimsList c ON
				t.ChassisNo = c.ChassisNo AND
				((t.RepairDate < c.RepairDate - 10) OR (t.RepairDate > c.RepairDate + 10))
		WHERE
			t.ClaimNo NOT IN (SELECT ClaimNo FROM #currentclaims)
			INSERT INTO ClaimsList SELECT * FROM #tmpTrucks WHERE ClaimNo = @clno
			INSERT INTO #currentclaims SELECT @clno
		SET @LocalCount = @LocalCount + 1
	END
END

...
...
...

Table ClaimsList has by this point been populated with unique Chassis Numbers. More records may be required based on the value of @Counter. These additional records will duplicate existing ChassisNumbers but must not have RepairDates within +/- 10 days of an existing record for that ChassisNumber in ClaimsList. It doesn't matter if after this section there are still less than the total required records in ClaimsList (in other word there may not be @Counter records that meet the criteria).

The above code and all variations of Join and Where that I have tried retrieve records irrespective of the RepairDate criteria.

ClaimNo is int
ChassisNo is varchar(22)
RepairDate is datetime

Any help would be greatly appreciated.



[vampire][bat]
 
Problem solved. Although I had tried EXISTS and NOT EXISTS earlier, I had obviously got it wrong.


This does the trick:

Code:
		SELECT TOP 1
			@clno = t.ClaimNo, @chno = t.ChassisNo, @repdt = t.RepairDate
		FROM
			#tmpTrucks t
		WHERE
			NOT EXISTS 
				(SELECT c.ChassisNo, c.RepairDate 
					FROM ClaimsList c 
					WHERE
						t.ChassisNo = c.ChassisNo AND
						c.RepairDate BETWEEN t.RepairDate - 10 AND t.repairDate + 10)

[vampire][bat]
 
Btw. there is TOP clause without ORDER by...

------
[small]<this is sig>
select stuff(stuff(replicate('<P> <B> ', 14), 109, 0, '<.'), 112, 0, '/')
</this is sig>[/small]
[banghead]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top