2

我有包含两个 DATE 列的表。TS_customer 和 TS_verified

我正在寻找一种方法来获得结果,在第一列中我有日期,其中有人创建了用户 (TS_customer) 或有人得到了验证 (TS_verified)。

在第二列中,我希望 count(TS_customer) 按第一列分组。我想要按第一列分组的第三列计数(TS_verified)。

在注册日期可能有 0 个客户验证,在另一种情况下,在某人得到验证的日期有 0 个注册。

我想这应该很容易,但我现在已经花了很多时间。非常感谢一些帮助。我需要这个用于 excel 中的图表,所以我基本上希望有多少客户注册以及有多少客户得到验证,而无需麻烦地进行两次选择并手动组合它们。

编辑:链接到 SQLfiddle http://sqlfiddle.com/#!2/b14fc/1/0

谢谢

4

2 回答 2

4

首先,我们需要日期列表。

看起来像这样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

看看情况如何?我们逐步建立您的结果集。

于 2013-10-27T01:36:31.590 回答
0

我有点困惑为什么你创建了一个不能null在 TS_Customer 上保存值的小提琴,然后提到该字段可以保存null值。

话虽如此,我已经修改了解决方案以使用null值,并且仍然非常高效和简单:

SELECT days, sum(custCount) custCount, sum(verifCount) verifCount FROM (
  SELECT DATE(TS_customer) days, count(*) custCount, 0 verifCount
  FROM customer
  WHERE TS_customer IS NOT NULL
  GROUP BY days
  UNION ALL
  SELECT DATE(TS_verified) days, 0, count(*)
  FROM customer
  WHERE TS_verified IS NOT NULL
  GROUP BY days
) s
GROUP BY days

我还在这里创建了一个包含一些空值的不同小提琴。

于 2013-10-27T02:23:14.330 回答