请参阅下面的SQL查询,它会计算CheckDate
在MatchSales
字段上 - 它无法实现我想要的样子。它应该找到D.MobileNO
(取决于CheckDate
)与S.mobile
的匹配(检查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
答案 0 :(得分: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
没有它你将全面扫描乳制品
答案 1 :(得分: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