我的数据库中有两个表。两个表中的列及其数据类型如下所示。假设两个表都存储了 3 台机器的数据。每台机器都有两个 s_id,通过使用它们,我将选择特定机器的所需数据。
每台机器的 s_id 是
m1 59,07
m2 60,92
m3 95,109
Table "public.table_a"
Column | Type | Modifiers | Storage | Stats target | Description
--------------+-----------------------------+-----------+---------+--------------+-------------
ettime | timestamp without time zone | | plain | |
sn | numeric | | main | |
s_id1 | numeric | | main | |
e_id1 | numeric | | main | |
Indexes:
"table_a_sn_key" UNIQUE CONSTRAINT, btree (sn)
Has OIDs: no
Table "public.table_b"
Column | Type | Modifiers | Storage | Stats target | Description
--------------+-----------------------------+-----------+----------+--------------+-------------
sn | numeric | | main | |
ettime | timestamp without time zone | | plain | |
value | text | | extended | |
comment | text | | extended | |
l_id | numeric | | main | |
n_id | numeric | | main | |
ettime.y | timestamp without time zone | | plain | |
s_id2 | numeric | | main | |
e_id2 | numeric | | main | |
Indexes:
"table_b_sn_key" UNIQUE CONSTRAINT, btree (sn)
Has OIDs: no
通过使用以下脚本,我将获得所需的结果。
库(RPostgreSQL)
M1 <- dbGetQuery(con, "select
a.r_date::date date,
downgraded,
total,
round(downgraded::numeric/total* 100, 2) percentage
from (
select date_trunc('day', eventtime) r_date, count(*) downgraded
from table_b
where s_id2 in (59,07)
group by 1
) b
join (
select date_trunc('day', eventtime) r_date, count(*) total
from table_a
where s_id1 in (59,07)
group by 1
) a
using (r_date)
order by 1")
因为我不是编程背景,所以我对每台机器都使用上述完整的查询语句
M2 <- dbGetQuery(con, "select
a.r_date::date date,
downgraded,
total, ........
........
M3 <- dbGetQuery(con, "select
a.r_date::date date,
downgraded,
total,.....
.........
在我的情况下,是否可以使用循环而不是对每台机器使用查询。这样在一个查询中我将获得所有机器数据。
有人可以用我的例子告诉我如何做这些。实际上,我需要运行 6 个单独的脚本,并且在每个脚本中我需要三台不同机器的数据。