是否可以根据where子句更改虚拟列值?
我有这张桌子:
[computername] [computerlocation] [starttime] [endtime]
computer, siteA, 1457537657, 1457532657
computer2, siteB, 1457547657, 1457546657
computer3, siteB, 1457237657, 14575237657
我想看看有多少台计算机,在给定的站点和给定的时间范围内,我目前使用的查询是:
select count(*), computerlocation
from table
where site like "site%"
and starttime <= "1457532657" and endtime >= "1457532657"
group by computerlocation
但是,目前我必须运行此查询数百次来创建一个图表,该图表显示一段时间内有多少台计算机。
是否可以制作这样的东西:
select count(*), computerlocation, "null" as time
from table
where site like "site%"
and ( (starttime <= "1457532657" and endtime >= "1457532657" as time="timeA")
OR (starttime <= "1457532357" and endtime >= "1457532357" as time="timeB")
OR (starttime <= "1457532651" and endtime >= "1457532651" as time="timeC")
)
group by time, computerlocation
答案 0 :(得分:0)
您使用CASE
expresion
首先创建虚拟列,然后执行group by
SELECT time_group, computerlocation, count(*)
FROM (
SELECT computerlocation,
CASE WHEN (starttime <= '1457532657' and endtime >= '1457532657') THEN 'timeA'
WHEN (starttime <= '1457532357' and endtime >= '1457532357') THEN 'timeB'
WHEN (starttime <= '1457532651' and endtime >= '1457532651') THEN 'timeC'
ELSE 'N/A'
END as time_group
from table
where site like 'site%'
) T
GROUP BY time_group, computerlocation
btw双引号表示"fieldname"
单引号表示字符串'string'
你应该检查BETWEEN
比较器,应写为
WHERE '1457532657' BETWEEN starttime AND endtime