2017-03-23 1 views
0

jdbcを使用してpostgresqlで次のクエリを使用して1日分のデータを取得しています。すぐにデータを取得する方法

int[] days={1,2,3,4,5,6,9,12,18,24} 

for(i=0;i<days.length;i++){ 
    //connect to database 
    String sql="select id,extract ('day' from time) as day,count(*) as count from public.data where time>='2016-10-'"+days[i]+'06:00:00' and time<='2016-10-"+days[i]+" 09:00:00' group by id,day "; 
    //execute sql and close connection 
} 

現在のクエリ(ループ内の1回の実行が)、それが毎日のために提供します。このよう

id day  count 
___ ___  _____ 
1  1   10 
2  1   12 
3  1   18 

を与えます。 これは毎日行われ、結果セットをCSVとして書いています。その代わりに、多くのSQL文を実行するのではなく、期間6から9の間に毎日のカウントを含むresulset全体を取得できますか?すべて一度

id day  count 
___ ___  _____ 
1  1   10 
2  1   12 
3  1   8 
1  2   10 
2  2   9 
3  2   18 
1  3   10 
2  3   12 
3  3   27 

のように任意の助けが

答えて

1

を使用する必要があり、構文エラーまたはSQLインジェクションを引き起こす可能性があります:

select id, 
     extract(day from time) as day, 
     count(*) as count 
from public.data 
where extract(day from time) = any (array[1,2,3,4,5,6,9,12,18,24]) 
    and time::date between date '2016-10-01' and date '2016-10-31' 
    and time::time between time '06:00:00' and time '09:00:00' 
group by id,day 

私はtimeではありません願っていますその列の本名

0

を高く評価されますで抽出(時間から日)のフィルタを用いたもので、すべてを使用することができます日と6と8

間(時間から1時間)を抽出します

:休止状態のクエリでパラメータマッピングに日数を使用する場合は、sqlと同等の値を使用できます。

0

まずあなたはあなたのクエリに問題があります。

日は2 ''なく""の間で次のようになります。

String sql="... where time>="2016-10-"+days[i]+"... 
//--------------------------^--------^------------ 

あなたのクエリは次のようになります。

String sql="select id,extract ('day' from time) as day,count(*) as count 
      from public.data where time>='2016-10-"+days[i]+" 06:00:00' 
      and time<='2016-10-"+days[i]+" 09:00:00' group by id,day "; 

第2あなたは代わりに、あなたは、単一のステートメントに必要な一切のループを、これを行うことはできないのPreparedStatement

+0

バッチ処理を使用することはありません。 – Kayaman

+0

はいこれは本当です@カヤマン私はそれを編集する –

関連する問題