2

我有 2 个不同的表格、用户和投票。我想查询按日期计算总用户数和总票数(不是总和)。 用户

id | created_at

选票

id | created_at

我希望结果如下所示:

date       | total users | total votes
2012-06-01 | 50          | 90
2012-06-01 | 23          | 0*
2012-06-01 | 80          | 12

*应该考虑到有些日子没有投票

我知道如何进行 2 个单独的查询

SELECT DATE(created_at), count(id)
FROM vote
GROUP by DATE(created_at)
ORDER by DATE(created_at) DESC

但我不知道如何加入他们。

4

3 回答 3

1

尝试这个:

SELECT
  DATE(created_at),
  SUM(CASE WHEN `Type` = 'Votes' THEN 1 ELSE 0 END) AS 'TotalVotes',
  SUM(CASE WHEN `Type` = 'Users' THEN 1 ELSE 0 END) AS 'TotalUsers'
FROM
(
    SELECT created_at, 'Votes' `Type` FROM vote
    UNION ALL
    SELECT created_at, 'Users'        FROM Users
) t
GROUP by DATE(created_at)
ORDER by DATE(created_at) DESC
于 2013-01-01T08:53:25.277 回答
0
SELECT DATE(created_at),SUM(usercolumnname) as totalusers,
SUM(//votescolumnname) as totalvotes from users u,votes v
where u.date=v.date
GROUP BY u.DATE(created_at)
ORDER BY u.DATE(created_at) DESC
于 2013-01-01T08:58:35.643 回答
0

尝试这个:

SELECT created_at, SUM(votes) AS 'TotalVotes', SUM(users) AS 'TotalUsers'
FROM(SELECT DATE(created_at) created_at, COUNT(ID) votes, 0 users 
      FROM votes GROUP BY DATE(created_at)
     UNION 
     SELECT DATE(created_at) created_at, 0 votes, COUNT(ID) users 
     FROM Users GROUP BY DATE(created_at)) t
GROUP BY created_at
ORDER BY created_at DESC
于 2013-01-01T09:01:35.267 回答