我有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
但我不知道如何加入他们。
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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