java - 如何一次性获取数据

标签 java sql postgresql jdbc

我正在使用以下查询使用 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 期间每天计数的整个结果集,而不是执行许多 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 
<小时/>

我确实希望时间不是该专栏的真实名称

关于java - 如何一次性获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42970024/

相关文章:

java - 将 ByteArray 添加到整数

java热点从服务器到客户端

SQL(ite) 过滤一对多表

postgresql - 使用 psycopg2 在不执行查询的情况下获取 PostgreSQL 结果集列类型

java - HTTP 状态 500 - java.lang.NoClassDefFoundError : java/time/temporal/TemporalField when run app on OpenShift

postgresql - 什么是备份 postgresql 数据库 : pg_dump VS pg_basebackup? 的推荐方法

java - Android 中的混沌多线程

java - 如何锁定公共(public)实用程序类中的各个方法?

mysql - 通过加入 MYSQL 在查询结果中获得位置

mysql - Ruby on Rails 表名 : what's permitted?