データベースに 2 つのテーブルがあります。両方のテーブルの列とそのデータ型を以下に示します。両方のテーブルに 3 台のマシンのデータが格納されているとします。各マシンには 2 つの 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,.....
.........
私の場合、マシンごとにクエリを使用する代わりに、ループを使用することは可能ですか。1 つのクエリですべてのマシン データを取得できるようにします。
誰かが私の例でこれらを行う方法を教えてもらえますか? 実際には、6 つの個別のスクリプトを実行する必要があり、各スクリプトには 3 つの異なるマシンのデータが必要です。