sql - 表中每天的值总和

标签 sql postgresql datetime aggregate-functions

我的 table :

Dataid  date        register_type  read_value
77      2012-08-15  gen            20
77      2012-08-15  solar          48
77      2012-08-16  gen            39
77      2012-08-16  gen            22
80      2012-07-11  gen            11
80      2012-07-12  id             23
91      2012-02-01  id              4
91      2012-02-01  gen            59
91      2012-02-08  gen            18

I would like, for each day, to do the sum of the read_values for only the "gen" register_type. I basically want the query to return the following table:

dataid  date        daily_value
77      2012-08-15  20.00
77      2012-08-16  61.00
80      2012-07-11  11.00
91      2012-02-01  59.00
91      2012-02-08  18.00

I tried the following query, but it does not work:

select 
    dataid, 
    date_trunc('day', timestamp_localtime) as truncated_day,
    substring(cast(date_trunc('day', timestamp_localtime) as text)
              from 1 for 10) as date,            
    sum(read_value) as daily_gen
where register_type like ‘%gen%’
from table
group by dataid, date_trunc('day', timestamp_localtime) 
order by dataid, truncated_day

我将如何编写此查询?

最佳答案

在 Postgres 中工作:

SELECT dataid, date, sum(read_value) AS daily_value
FROM   tbl
WHERE  register_type = 'gen'
GROUP  BY 1,2
ORDER  BY 1,2

或者您的名为 date 的列实际上不是日期?
如果它实际上是一个 timestamp,请将我的查询中的 date 替换为 date::date(将 timestamp 转换为 date) 它应该可以工作。
(你不应该使用 reserved wordsdate 作为标识符开始,即使 Postgres 允许它。)

关于sql - 表中每天的值总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14369526/

相关文章:

Python 给定日期、时间、小时...我怎样才能得到它的 ISO ZULU 格式

python - 使用 Selenium 抓取测试一致性

mysql: 'r' 是什么意思?

mysql - SQL 没有保存正确的浮点值

mysql查询问题

ruby - 如何对 Ruby 的 Postgres 驱动程序和 DBI 进行故障排除?

sql - 在oracle中删除然后添加约束失败

sql - 如何在没有关键 postgres 的情况下使用 json 数组连接 2 个表

c# - 在 PostgreSQL 中锁定表

datetime - ISO 8601 日期时间表示