首先,我们需要日期列表。
看起来像这样http://sqlfiddle.com/#!2/b14fc/14/0:
SELECT DISTINCT days
FROM (
SELECT DISTINCT DATE(TS_customer) days
FROM customer
UNION
SELECT DISTINCT DATE(TS_verified) days
FROM customer
) AS alldays
WHERE days IS NOT NULL
ORDER BY days
接下来,我们需要按天汇总客户数量。这很容易http://sqlfiddle.com/#!2/b14fc/16/0:
SELECT DATE(TS_customer) days, COUNT(TS_customer)
FROM customer
GROUP BY days
每天的验证摘要同样简单。
接下来我们需要将这三个子查询连接在一起 http://sqlfiddle.com/#!2/b14fc/29/0。
SELECT alldays.days, custcount, verifycount
FROM (
SELECT DISTINCT DATE(TS_customer) days
FROM customer
UNION
SELECT DISTINCT DATE(TS_verified) days
FROM customer
) AS alldays
LEFT JOIN (
SELECT DATE(TS_customer) days, COUNT(TS_customer) custcount
FROM customer
GROUP BY days
) AS cust ON alldays.days = cust.days
LEFT JOIN (
SELECT DATE(TS_verified) days, COUNT(TS_verified) verifycount
FROM customer
GROUP BY days
) AS verif ON alldays.days = verif.days
WHERE alldays.days IS NOT NULL
ORDER BY alldays.days
最后,如果您想0
显示而不是(null)
在没有任何客户和/或验证的日子里显示,请将 SELECT 行更改为此http://sqlfiddle.com/#!2/b14fc/30/0。
SELECT alldays.days,
IFNULL(custcount,0) AS custcount,
IFNULL(verifycount,0) AS verifycount
看看情况如何?我们逐步建立您的结果集。