我的SELECT查询如下所示需要插入到表wifi_user_analytic_dy中。
SELECT
date(acctstarttime)
, round(avg(acctsessiontime),2)average_connected_ap
, calledstationid
FROM ( SELECT acctstarttime, acctsessiontime, calledstationid
FROM wifi_radacct
WHERE acctstoptime <> ''
and date(acctstarttime)= date_trunc('day', now()) -'1 day'::interval
)a
group by calledstationid, date(acctstarttime)
基于查询的示例结果:
| date | average_connected_ap | calledstationid |
| 2017-12-06 | 1000 | publica |
| 2017-12-06 | 800 | tumis |
| 2017-12-06 | 500 | penyet |
以上查询将根据日期和ap找到平均连接,并更新到表wifi_user_analytic_dy中。下面是表wifi_user_analytic_dy中的预期结果。
| date | ap | average_connected_duration_ap |
| 2017-12-06 | publica | 1000 |
| 2017-12-06 | tumis | 800 |
| 2017-12-06 | penyet | 500 |
我正在尝试从上面的SELECT查询中复制average_connected_ap数据,并在列average_connected_duration_ap更新表wifi_user_analytic_dy。下面的UPDATE查询未生成正确的结果。它将相同的值复制到所有ap。
如何更正此更新查询。
UPDATE wifi_user_analytic_dy B
SET avg_connected_duration_ap = ( select round(avg(wifi_radacct.acctsessiontime),2)
from wifi_radacct
where date(acctstarttime)= date_trunc('day', now()) -'1 day'::interval
)
FROM wifi_radacct A
WHERE A.calledstationid=B.ap and A.date(acctstarttime)= B.date
;
希望有人可以告诉我。
答案 0 :(得分:0)
你可以使用CTE。类似的东西:
WITH C as
( select
D.ap, D.bate,
(select round(avg(wifi_radacct.acctsessiontime),2)
from wifi_radacct
where date(acctstarttime)= date_trunc('day', now()) -'1 day'::interval) as V
FROM wifi_radacct A
JOIN wifi_user_analytic_dy D
ON A.calledstationid=D.ap and A.date(acctstarttime)= D.date
)
UPDATE wifi_user_analytic_dy B
SET avg_connected_duration_ap = V
FROM C where A.calledstationid=C.ap and A.date(acctstarttime)=C.date
但是你不需要子查询:
WITH C as
( select
D.ap, D.bate,
round(avg(A.acctsessiontime),2
from wifi_radacct
where date(acctstarttime)= date_trunc('day', now()) -'1 day'::interval) as V
FROM wifi_radacct A
JOIN wifi_user_analytic_dy D
ON A.calledstationid=D.ap and A.date(acctstarttime)= D.date
GROUP BY D.ap,D.date
)
UPDATE wifi_user_analytic_dy B
SET avg_connected_duration_ap = V
FROM C where A.calledstationid=C.ap and A.date(acctstarttime)=C.date
并且可能不需要加入。