0

是否可以根据 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
4

1 回答 1

0

你使用一个CASE表达式

首先创建虚拟列,然后执行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
于 2016-03-09T19:03:19.027 回答