Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

postgresql - SQL request to group and sum numbers by their day of creation

Let me explain this. I have a table where I have two important fields I need : The first one is a double, and the second one is a date.

I would like to make a requests that groups entries by YYYY-MM-DD, and adds each field of the double by group.

For example, I have two entries the same day :

   |   amount    |    date
1  |    100      | 2010-01-01
2  |    200      | 2010-01-01

What I need is :

1  |     300     | 2010-01-01

Is that possible ? For the moment here is my request :

 SELECT DISTINCT ON (d) amount, to_char(datecreation, 'YYYY-MM-DD') d
   FROM mytable
  GROUP BY d, amount
  ORDER BY d ASC;

What I get is :

1  | 100   | 2010-01-01

It doesn't add the grouped amounts.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
select sum(amount), date from mytable group by date order by sum(amount) ASC;

If your dates have a time part, then

select sum(amount), to_char(date, 'YYYY-MM-DD') from mytable group by to_char(date, 'YYYY-MM-DD') order by sum(amount) ASC;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...