Home > Enterprise >  Join two table with where
Join two table with where

Time:03-02

I have two queries from two views

Query 1:

SELECT sum(cancels) as cancelcount,codeprogram 
FROM CanceliTems 
WHERE date_save BETWEEN '1/21/2022' AND 
'2/20/2022' and usercode = 8066
GROUP By codeprogram

and the result is:

cancelcount codeprogram
7 3001
7 3002
2 3006

Query 2:

SELECT SUM(sellcount) sellcount,codeprogram,price 
FROM sells
WHERE date_save BETWEEN '1/21/2022' AND '2/20/2022' and usercode = 8066
GROUP By codeprogram,price

and the result is:

sellcount codeprogram price
27 3001 10000
25 3000 20000
9 3006 25000
3 3011 15000
8 3008 11000
55 3002 50000

How can I join two views and then subtract the number of cancel from the number of sales and finally multiply the number by the price, At a specified date range?

In every view I have field date_save (datetime) and it filled by getdate() and usercode.

finalcount = (sellcount - cancelcount) * price

I want the final output to be as follows:

finalcount codeprogram price
20 3001 200000
25 3000 500000
7 3006 175000
3 3011 45000
8 3008 88000
47 3002 2350000

Thanks

CodePudding user response:

One way you can try to use two subqueries with OUTER JOIN

SELECT sellcount - ISNULL(cancelcount,0) finalcount,
       t1.codeprogram,
       t1.price
FROM (
    SELECT SUM(sellcount) sellcount,codeprogram,price 
    FROM sells
    WHERE date_save BETWEEN '1/21/2022' AND '2/20/2022' and usercode = 8066
    GROUP By codeprogram,price
) t1
LEFT JOIN (
    SELECT sum(cancels) as cancelcount,codeprogram 
    FROM CanceliTems 
    WHERE date_save BETWEEN '1/21/2022' AND '2/20/2022' and usercode = 8066
    GROUP By codeprogram
) t2 ON t1.codeprogram = t2.codeprogram

From your query, you might rewrite as below, use UNION ALL combine sells & CanceliTems and make a flag to represent that 1 is positive number, 2 is negative number then use condition aggregate function.

SELECT SUM(CASE WHEN flag = 1 THEN sellcount ELSE - sellcount END),codeprogram,SUM(price) price
FROM (
    SELECT sellcount,codeprogram,price , 1 flag
    FROM sells
    WHERE date_save BETWEEN '1/21/2022' AND '2/20/2022' and usercode = 8066
    UNION ALL
    SELECT cancels,codeprogram,0 , 2
    FROM CanceliTems
    WHERE date_save BETWEEN '1/21/2022' AND '2/20/2022' and usercode = 8066
) t1
GROUP BY codeprogram
  • Related