开发者

MySQL: list of sum for several conditions in one SQL statement

开发者 https://www.devze.com 2023-01-06 22:19 出处:网络
I have a problem with a MySQL statement: select sum(x) as \"sum\", \"01.06.2010\" as \"date\" from ( select distinct a.id as ID, a.dur as x from b_c

I have a problem with a MySQL statement:

select sum(x) as "sum", "01.06.2010" as "date" from (
   select distinct a.id as ID, a.dur as x from b_c 
      inner join c on b_c.c_id = c.id 
      inner join a on c.id = a.c_id 
      inner join a_au on a.id = a_aud.id 
      inner join d on a_au.rev = d.rev 
      where 
         b_c.b_id = 30 and 
         a_au.stat != 1 and 
         DATE(FROM_UNIXTIME(rtime)) = DATE('2010-06-01')
) AS SubSelectTable;

This statement returns one row with the colums "sum" and "date".

Now I have not only one date ('2010-06-01'), I have many dates I have to get the sum() of it, but not in one single row. I want to have per day one result row.

So, for example, the statement above returns me

sum            date
-------------------
 20      01.06.2010

Now I have the dates 2010-06-01, 2010-06-02, 2010-06-03, ... What I can do is to write for every date one sql statement changing the DATE. So if I have 10 dates, I will have 10 sql statements for the database. But I did want it with one SQL statement, and the result should not be the sum of all given dates, I want to have one result row per date. So the result should like that:

sum            date
-------------------
 20      01.06.2010
133    开发者_C百科  02.06.2010
 19      03.06.2010
 88      04.06.2010
...             ...

How can I do this? Does anyone know?

Thanks a lot in advance & Best Regards.


Use the mysql GROUP BY command. Completely untested code example:

select sum(x) as "sum", date as "date" from (
   select distinct a.id as ID, a.dur as x, DATE(FROM_UNIXTIME(rtime)) as date from b_c 
      inner join c on b_c.c_id = c.id 
      inner join a on c.id = a.c_id 
      inner join a_au on a.id = a_aud.id 
      inner join d on a_au.rev = d.rev 
      where 
         b_c.b_id = 30 and 
         a_au.stat != 1
) AS SubSelectTable
group by date;

See: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号