表中每天的值总和

时间:2013-01-16 23:06:11

标签: sql postgresql datetime aggregate-functions

我的表:

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

我希望每天只为“gen”read_valuesregister_type的总和。我基本上希望查询返回下表:

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

我尝试了以下查询,但它不起作用:

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

我该如何撰写此查询?

2 个答案:

答案 0 :(得分:5)

在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),它应该有效。
(即使Postgres允许,也不应该使用像date这样的reserved words作为标识符。)

答案 1 :(得分:2)

在SQL Server中,以下方法可行:

SELECT SUM(read_value) AS daily_value, dataid, date
FROM (SELECT *, CONVERT(VARCHAR(10),date,105) AS newdate FROM Table)
WHERE type = 'gen'
GROUP BY newdate

对于MySQL,请改用:

SELECT SUM(read_value) AS daily_value, dataid, date
FROM (SELECT *, DATE_FORMAT(newdate, '%d-%m-%Y') AS day FROM Table)
WHERE type = 'gen'
GROUP BY newdate

子查询是必需的,因为GROUP BY不支持通常的聚合函数。但是,仅当date是日期时间时才需要这样做。如果它只是一个日期,那么就不需要从中提取日期