我有一个会计表,从这张表我监控用户的活动。我有以下3个查询: 第一
select count(distinct username),
DATE_FORMAT(StartTime,'%H %d/%m/%y')
from acct
where date(starttime) = date '2014-10-02'
group by DATE_FORMAT(StartTime,'%H %d/%m/%y')
第二
select count(distinct username),
DATE_FORMAT(UpdateTime,'%H %d/%m/%y')
from acct
where date(updatetime) = date '2014-10-02'
group by DATE_FORMAT(UpdateTime,'%H %d/%m/%y')
第三
select count(distinct username),
DATE_FORMAT(StopTime,'%H %d/%m/%y')
from acct
where date(stoptime) = date '2014-10-02'
group by DATE_FORMAT(StopTime,'%H %d/%m/%y')
我有点困惑,有可能让它们成为一个查询吗?我想检查当天每小时有多少用户在线。你能指导我在哪里解决我的问题吗? 感谢
字段starttime,updatetime和stoptime是datetime。
答案 0 :(得分:1)
如果您在所有选择查询中获取相同数量的字段,则可以使用UNION
。但在这种情况下,您可能只想使用OR
:
select COUNT(DISTINCT username) AS count_distinct_users,
CASE WHEN date(StartTime) = date '2014-10-02'
THEN DATE_FORMAT(StartTime,'%H %d/%m/%y')
WHEN date(UpdateTime) = date '2014-10-02'
THEN DATE_FORMAT(UpdateTime,'%H %d/%m/%y')
WHEN date(StopTime) = date '2014-10-02'
THEN DATE_FORMAT(StopTime,'%H %d/%m/%y')
END AS date
from acct
where date(StartTime) = date '2014-10-02'
or date(UpdateTime) = date '2014-10-02'
or date(StopTime) = date '2014-10-02'
group by date
<强> sqlFiddle demo 强>
答案 1 :(得分:0)
使用UNION:
尝试此操作select count(distinct username),
DATE_FORMAT(StartTime,'%H %d/%m/%y')
from acct
where date(starttime) = date '2014-10-02'
group by DATE_FORMAT(StartTime,'%H %d/%m/%y')
UNION
select count(distinct username),
DATE_FORMAT(UpdateTime,'%H %d/%m/%y')
from acct
where date(updatetime) = date '2014-10-02'
group by DATE_FORMAT(UpdateTime,'%H %d/%m/%y')
UNION
select count(distinct username),
DATE_FORMAT(StopTime,'%H %d/%m/%y')
from acct
where date(stoptime) = date '2014-10-02'
group by DATE_FORMAT(StopTime,'%H %d/%m/%y')