我正在尝试以下列格式生成表格。
Proday | 2014-04-01 | 2014-03-01
--------------------------------
1 | 12 | 17
2 | 6 | 0
7 | 0 | 24
13 | 3 | 7
Prodays(两个时间戳之间的持续时间)是计算值,月份数据是COUNT。我可以输出一个月的数据,但是在将查询加入其他月份时遇到了麻烦。每个月的指数(prodays)可能不匹配。例如,2014-04-01可能没有Prodays 7的任何数据,而2014-03-01可能没有Proday 2.应该表示0或null。
我怀疑FULL OUTER JOIN是应该做的诀窍。但是已经读过Mysql中不可能的内容吗?
这是获取单个月数据的查询:
SELECT round((protime - createtime) / 86400) AS prodays, COUNT(id) AS '2014-04-01'
FROM `tbl_users` as t1
WHERE status = 1 AND DATE_FORMAT(FROM_UNIXTIME(createtime),'%Y-%m-%d') >= '2014-04-01'
AND DATE_FORMAT(FROM_UNIXTIME(createtime),'%Y-%m-%d') <= LAST_DAY('2014-04-01')
GROUP BY prodays
ORDER BY `prodays` ASC
如何加入/联合其他查询以创建2014-03-01的列?
答案 0 :(得分:1)
您希望使用条件聚合 - 即将过滤逻辑从where
子句移到select
子句:
SELECT round((protime - createtime) / 86400) AS prodays,
sum(DATE_FORMAT(FROM_UNIXTIME(createtime),'%Y-%m-%d') >= '2014-04-01' AND
DATE_FORMAT(FROM_UNIXTIME(createtime),'%Y-%m-%d') <= LAST_DAY('2014-04-01')
) as `2014-04-01`,
sum(DATE_FORMAT(FROM_UNIXTIME(createtime),'%Y-%m-%d') >= '2014-03-01' AND
DATE_FORMAT(FROM_UNIXTIME(createtime),'%Y-%m-%d') <= LAST_DAY('2014-03-01')
) as `2014-03-01`
FROM `tbl_users` as t1
WHERE status = 1
GROUP BY prodays
ORDER BY `prodays` ASC;