Click here to Skip to main content
15,919,778 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Table_1
SQL
Table_1
Stockno|StartDate|ServiceTag|Modelno
123	2015-08-01	ABC	Inspiron
123	2015-06-01	DEF	Inspiron
123	2015-08-01	GHI	Inspiron
123	2015-08-01	JKL	Inspiron
456	2015-08-01	MNO	Galaxy
456	2015-07-01	PQR	Galaxy
456	2015-08-01	STU	Galaxy
456	2015-08-01	VWX	Galaxy
456	2015-08-01	ABC	Galaxy

Table_2
Stockno|TransDate|TransType|ServiceTag|Modelno
                                            
123	2015-08-04	2100	  ABC	  Inspiron
123	2015-08-19	2100	  GHI	  Inspiron
456	2015-08-25	2100	  STU	  Galaxy
123	2015-07-25	2100	  DEF	  Inspiron



I have two tables.Table_1 is available stock. Table_2 is sold stock. I want remaining stock after sales. I wrote the following query,it works fine but the problem is it doesnt return Galaxy with service tag= ABC(not sold) since Inspiron(servicetag=ABC) is sold. So in remaining stock I should get totally 5 records instead I get only 4. How to correct this query?
SQL
 Select P.Stockno,P.Modelno,P.ServiceTag, Count(P.Stockno) as ClosingBal
From Table_1 as P
Where  P.ServiceTag  Not in (Select ServiceTag from Table_2 )
Group by P.Stockno,P.Modelno,P.ServiceTag
Posted
Comments
Tomas Takac 9-Sep-15 3:06am    
If servicetag is not enough to identify the sold stock then why don't you add more columns to the comparison? I guess you should compare on all three columns: Stockno, Modelno, ServiceTag.

1 solution

Change the NOT IN to an outer join and add the other fields to the missing conditions
SQL
SELECT  P.Stockno
       ,P.Modelno
       ,P.ServiceTag
       ,Count(P.Stockno) as ClosingBal
FROM    Table1 P
left OUTER
JOIN    Table2 t2
    ON  p.servicetag = t2.servicetag
    AND p.stockno = t2.stockno
    AND p.Modelno = t2.Modelno
WHERE   t2.servicetag IS NULL
    AND t2.stockno IS NULL
    AND t2.Modelno IS NULL
GROUP BY P.Stockno,P.Modelno,P.ServiceTag
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900