Search code examples
sqlsubquerycorrelated-subquery

how to write SQL Correlated subqueries


I have two table ItemsDetails and ItemsSquare

**ItemsDetails** table have following column

ItmDtlId P.K

Itmid F.K

AssetId F.k

Qty 

TDate

Approved

**ItemsSquare** table have following column

ItmSqrId P.k

ItmDtlId F.k

ItmSqQty

Date

From ItemsDetails table i want to show all the records from ItemDetails table also records from ItemsSquare table which is having ItmDtlId same as in ItemDetails and then compare Quantity from ItemDetails table and Itemsquare table as Qty > ItmSqQty

basically i want to access columns of ItemsSquare table from ItemDetails table based o ItmDtId as there is no relationship of first table with second table

i am using sql Correlated subquery as follow but i am not getting expected result

Here is my sql query

SELECT itd.ItmDtlId
     , it.Itmid
     , itd.Qty
     , itd.Approved
     , as.Assetid
     , as.Assetname
     , itd.TDate 
  from ItemsDetails itd
  join Item it 
    on itd.Itmid = it.Itmid
  join Assets as 
    on itd.Assetsid = as.Assetsid
 WHERE itd.Approved = 1 
   and itd.ItmDtlId = (SELECT itd.ItmDtlId FROM ItemsSquare its WHERE itd.ItmDtlId = its.ItmDtlIdand itd.Qty > ItmSqQty) 

Please suggest me how i can write Sql subquery effectively to get desired result


Solution

  • Is that possible that you are referencing your subquery wrongly?

    Instead of:

    ...
    AND itd.ItmDtlId = (
        SELECT itd.ItmDtlId 
        FROM ItemsSquare its
        WHERE itd.ItmDtlId = its.ItmDtlIdand
          AND itd.Qty > its.ItmSqQty
    )
    

    To:

    ...
    AND itd.ItmDtlId = (
        SELECT its.ItmDtlId 
        FROM ItemsSquare its
        WHERE itd.ItmDtlId = its.ItmDtlIdand
          AND itd.Qty > its.ItmSqQty
    )