简体   繁体   中英

SQL Retest same table that returns 1st row

I'm a beginner when it comes to sql and this one is a little over my head and hoping someone could point me in the right direction..

I have written a query that correctly returns one row from the right hand table but I need to add another test in the final where clause that rechecks the table and checks all entries in the field contitems.tofollow and looks for values greater than zero's which match the original contracts.ContNo row returned..

SELECT Contracts.*, Contitems.*
FROM   dbo.Contracts 
INNER JOIN dbo.ContItems 
 ON dbo.ContItems.RECID =       
  (SELECT TOP(1) RECID 
   FROM dbo.ContItems 
   WHERE (ContItems.CONTNO = dbo.Contracts.CONTNO))
WHERE  dbo.Contracts.SOURCE = 2 
 and (contracts.custom = 1 or contitems.tofollow > 0) 
 and contracts.status not in (4,9)

I need to replace the contitems.tofollow > 0 with a test that rechecks the whole contitems.tofollow results for each ContNO but no idea how to achieve it.. can anyone help..?

i thought of another way to do this by selecting the single row with the greatest TOFOLLOW quantity -- no further test necessary..

   SELECT Contracts.*, Contitems.*
   FROM   dbo.Contracts 
   INNER JOIN dbo.ContItems 
   ON dbo.ContItems.RECID =       
  (SELECT TOP(1) RECID 
  FROM dbo.ContItems 
  WHERE (ContItems.CONTNO = dbo.Contracts.CONTNO)
   ORDER BY TOFOLLOW Desc)
 WHERE  dbo.Contracts.SOURCE = 2 
 and (contracts.custom = 1 or contitems.tofollow > 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM