簡體   English   中英

如何一次獲取數據

[英]How to get Data at once

我正在使用以下查詢使用jdbc在postgresql中獲取一天的數據。

  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
}

當前查詢(循環中運行一次)給出

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

這樣,它會給每一天。 但這是每天完成的,我將結果集編寫為csv。相反,我可以獲取包含6至9期間每天計數的整個resulset而不是執行許多sql語句嗎?立刻喜歡

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

任何幫助表示贊賞

您可以在單個語句中執行此操作,而無需循環:

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不是該專欄的真實名稱

您可以使用:days中的過濾器WHERE extract(時間間隔)和6至8之間的時間間隔(hour)來合而為一。

:days用於休眠查詢中的參數映射,可以使用等效的sql。

首先,您在查詢中遇到問題:

日期應介於兩個''之間,而不是""

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 ";

其次,您不必使用Statement可能會導致語法錯誤或SQL注入,而必須使用PreparedStatement

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM