1

我有 2 张桌子:投票和用户。我想在当天的总票数旁边显示新注册用户的总票数(不是总票数)。

查询的时间范围可以是全部,我可以稍后添加从 - 到时间范围。

因此,如果我每个日期 X 有 10 票,我想知道新用户生成了多少票,返回用户生成了多少,以及有多少新的和返回的投票(* 还包括未投票的新用户)。

投票:

id | vote | user_id | created_at
1  | 30   | 28      | 2012-06-10
1  | 12   | 15      | 2012-06-10
1  | 30   | 28      | 2012-06-10
...

用户:

users_ id | created_at
28        | 2012-06-01
29        | 2012-06-03
30        | 2012-06-10
...

我希望得到的结果是:

Date | total votes | votes for new | votes for returning | total new users | total returning users

谢谢!

----- 当前代码:

        SELECT
      DATE(created_at) AS Date,
      SUM(CASE WHEN `Type` = 'Votes' THEN 1 ELSE 0 END) AS 'Total Votes',
      SUM(CASE WHEN `Type` = 'Users' THEN 1 ELSE 0 END) AS 'Total Users'
    FROM
    (
        SELECT created_at, 'Votes' `Type` FROM votes
        UNION ALL
        SELECT created_at, 'Users'        FROM users
    ) t
    GROUP by DATE(created_at)
    ORDER by DATE(created_at) DESC
4

1 回答 1

0

我会考虑在几个查询中分解它。如果我理解你的正确,这应该是你正在寻找的。

所有投票日期:

SELECT created_at AS date, COUNT(*) AS totalvotes FROM votes GROUP BY created_at;

新用户公关日期的所有投票

SELECT v.created_at AS date, COUNT(*) AS newuservotes FROM votes v INNER JOIN users u WHERE v.user_id = u.user_id AND v.created_at = u.created_at GROUP BY v.created_at;

老用户投票日期

The two numbers subtracted

如果您想在一个查询中完成全部内容:

SELECT totvotes.date AS date, totvotes.totalvotes AS totalvotes, IFNULL(newvotes.newuservotes, 0) AS newuservotes, totvotes.totalvotes-IFNULL(newvotes.newuservotes, 0) AS olduservotes
FROM 
(
SELECT created_at AS date, COUNT(*) AS totalvotes FROM votes GROUP BY created_at
) totvotes
LEFT JOIN
(
SELECT v.created_at AS date, COUNT(*) AS newuservotes FROM votes v INNER JOIN users u WHERE v.user_id = u.user_id AND v.created_at = u.created_at GROUP BY v.created_at
) newvotes ON totvotes.date = newvotes.date

用 mysql> select * from users 测试;

+---------+------------+
| user_id | created_at |
+---------+------------+
|       1 | 2012-06-01 |
|       2 | 2012-06-02 |
|       3 | 2012-06-03 |
+---------+------------+
3 rows in set (0.00 sec)

mysql> 从投票中选择 *;

+----+------+---------+------------+
| id | vote | user_id | created_at |
+----+------+---------+------------+
|  1 |   10 |       1 | 2012-06-01 |
|  2 |   20 |       1 | 2012-06-10 |
|  3 |   30 |       2 | 2012-06-02 |
|  4 |   40 |       2 | 2012-06-10 |
+----+------+---------+------------+
4 rows in set (0.00 sec)

结果:

+------------+------------+--------------+--------------+
| date       | totalvotes | newuservotes | olduservotes |
+------------+------------+--------------+--------------+
| 2012-06-01 |          1 |            1 |            0 |
| 2012-06-02 |          1 |            1 |            0 |
| 2012-06-10 |          2 |            0 |            2 |
+------------+------------+--------------+--------------+

类似的东西可以用于“从未投票”的用户等等

我不确定您对 SQL 的精通程度,所以如果有任何问题,请发表评论,我会更新答案。

于 2013-01-02T14:17:53.750 回答