简体   繁体   中英

How to join two tables with different condition

I'm just wondering how can I join these two queries?

  1. SELECT SUM(TOTAL_SALES) FROM TBL_SALES WHERE LOGIN_DATE >= '2020-01-03' AND LOGOUT_DATE < '2020-01-04'

  2. SELECT SUM(TOTAL_MONEY) FROM TBL_SALES_INFO WHERE LOGIN_DATE >= '2020-01-03' AND LOGOUT_DATE < '2020-01-04'

here's my code but I'm getting the wrong result:

SELECT SUM(A.TOTAL_SALES) AS TOTAL_SALES,
       SUM(B.TOTAL_MONEY) AS TOTAL_MONEY
FROM TBL_SALES A RIGHT JOIN
     TBL_SALES_INFO B
     ON A.SALES_NO= B.SALES_NO
WHERE A.LOGIN_DATE>= '2020-01-01 09:00:00' AND A.LOGOUT_DATE < '2020-01-02 09:00:00' AND
      B.LOGIN_DATE>= '2020-01-01 09:00:00' AND B.LOGOUT_DATE < '2020-01-02 09:00:00'

Your current queries are an entirely separate tables. The best I can see would be to just leave them as is, an aggregate in a top level SELECT :

SELECT
    (SELECT SUM(TOTAL_SALES) FROM TBL_SALES
     WHERE LOGIN_DATE >= '2020-01-03' AND LOGOUT_DATE < '2020-01-04') AS TOTAL_SALES,
    (SELECT SUM(TOTAL_MONEY) FROM TBL_SALES_INFO
     WHERE LOGIN_DATE >= '2020-01-03' AND LOGOUT_DATE < '2020-01-04') AS TOTAL_MONEY;

You might be over-complicating things with the a. and b. stuff? In addition, rather than a right join maybe an inner join would work better? Then you wouldn't need to sort by timestamps from both tables. You'd only need the total sales and timestamps based on one tables time.

It would help if you posted the results you were getting, even if they were incorrect.

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