左連接匹配數的問題

[英]Problem with Left Join - matching Number


See the SQL query below, it count the number of Yes and No between the CheckDate

查看下面的SQL查詢,它會在檢查日期之間計算Yes和No的數量

On the MatchSales field - it do not work how I wanted to be. It should find D.MobileNO (depending on the CheckDate) match to S.mobile (Check all record in the sales table)

在婚介銷售領域,我的理想狀態是行不通的。它應該找到D。MobileNO(取決於檢查日期)匹配到S。手機(查看銷售表中的所有記錄)

SELECT D.Username, 
    SUM(CASE WHEN D.type = 'Yes' AND UNIX_TIMESTAMP(CheckDate) >= $From_timestamp AND UNIX_TIMESTAMP(CheckDate) <= $To_timestamp THEN 1 ELSE 0 END) as Yes, 
    SUM(CASE WHEN D.type = 'No' AND UNIX_TIMESTAMP(CheckDate) >= $From_timestamp AND UNIX_TIMESTAMP(CheckDate) <= $To_timestamp THEN 1 ELSE 0 END) as No, 
    SUM(CASE WHEN S.mobile IS NULL THEN 0 ELSE 1 END) as MatchSales
FROM dairy as D 
   LEFT JOIN (SELECT DISTINCT mobile FROM sales) as S on D.MobileNo = S.mobile
WHERE source = 'Company' 
GROUP BY D.Username

2 个解决方案

#1


2  

simply add the Checkdate condition from your CASE to the where clause:

只需將檢查日期條件從您的案例添加到where子句中:

SELECT D.Username,      
      SUM(CASE WHEN D.type = 'Yes' THEN 1 ELSE 0 END) AS Yes,      
      SUM(CASE WHEN D.type = 'No'  THEN 1 ELSE 0 END) AS No,      
      SUM(CASE WHEN S.mobile IS NULL THEN 0 ELSE 1 END) AS MatchSales 
 FROM dairy AS D     
 LEFT JOIN (SELECT DISTINCT mobile FROM sales) AS S ON D.MobileNo = S.mobile 
 WHERE D.source = 'Company'  
 AND   UNIX_TIMESTAMP(D.CheckDate) >= $From_timestamp 
 AND   UNIX_TIMTIMESTAMP(D.CheckDate) <= $To_timestamp 
 GROUP BY D.Username

without it you will full scan dairy

沒有它,你將會完全掃描乳制品

#2


1  

-- I think this is how you do it:

——我想這就是你的做法:

SELECT SUM(Yes) AS Yes, SUM(No) AS No
FROM (
    SELECT D.Username, 
        (CASE WHEN D.type = 'Yes' AND UNIX_TIMESTAMP(CheckDate) >= $From_timestamp AND UNIX_TIMESTAMP(CheckDate) <= $To_timestamp THEN 1 ELSE 0 END) as [Yes], 
        (CASE WHEN D.type = 'No' AND UNIX_TIMESTAMP(CheckDate) >= $From_timestamp AND UNIX_TIMESTAMP(CheckDate) <= $To_timestamp THEN 1 ELSE 0 END) as [No], 
        (CASE WHEN S.mobile IS NULL THEN 0 ELSE 1 END) as MatchSales
    FROM dairy as D 
        LEFT JOIN (SELECT DISTINCT mobile FROM sales) as S on D.MobileNo = S.mobile
    WHERE source = 'Company' 
    GROUP BY D.Username
) T

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/08/12/72f4bb7337771ec980b6975f474322fb.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com