2011-08-12 114 views
1

請參閱下面的SQL查詢,指望它是數量和否CheckDate問題與左連接 - 匹配數

之間在MatchSales場 - 它不工作,我怎麼想是。它應該找到(取決於CheckDate)匹配S.mobileD.MobileNO(檢查所有記錄在sales表)

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

只是簡單地從CASE添加了checkdate條件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 

無它你會全面掃描奶製品

+0

在SUM? ..... – user622378

+1

不,在'source ='Company'之後# – judda

+0

掛上我會編輯以顯而易見 –

1

- 我認爲這是你如何做到這一點:

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 
+0

該查詢不起作用。它不喜歡[是]和[否]名稱 – user622378

+0

如果沒有括號? – tim