See the SQL query below, it count the number of Yes and No between the CheckDate
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)
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 (SE开发者_JS百科LECT DISTINCT mobile FROM sales) as S on D.MobileNo = S.mobile
WHERE source = 'Company'
GROUP BY D.Username
simply add the Checkdate condition from your CASE
to the where
clause:
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
-- 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
精彩评论