SELECT总票数为新&在mysql中返回用户

时间:2013-01-02 10:38:57

标签: mysql select

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

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

因此,如果我每个日期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

1 个答案:

答案 0 :(得分: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的>从用户中选择*;

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

的MySQL> select * from votes;

+----+------+---------+------------+
| 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方面有多精通,所以如果有任何问题请发表评论,我会更新ansver。