Mysql查询,选择,组&按分钟计算

时间:2012-12-07 10:33:53

标签: mysql sum group-by

我有一个像这样的数据库表:

id | donation_type | donation_amount | time_inserted
1    em1              20                2012-12-07 10:01:00
2    em1              50                2012-12-07 10:01:00
3    em1              100               2012-12-07 10:01:00
4    em1              150               2012-12-07 10:02:00
5    em1              100               2012-12-07 10:02:00
6    em1              30                2012-12-07 10:02:00
7    em1              40                2012-12-07 10:03:00
8    em1              65                2012-12-07 11:16:00

我想查询一下每分钟捐款的数量 我还要总结那一分钟的捐款金额。

所以我希望返回结果(使用上面的表格):

10:00:01 => 3, amount => 170 # 3 donations in 10:01:00, totaling £170
10:00:02 => 3, amount => 280 # 3 donations in 10:02:00, totaling £280
10:00:03 => 1, amount => 40 # 1 donation in 10:03:00, totaling £40
11:16:00 => 1, amount => 65 # 1 donation in 11:16:00, totaling £40

编辑 - 我希望SQL查询返回的示例

# Example of what I would like returned..

time                  |  donation_count  | donation_sum_in_minute
2012-12-07 10:01:00           3                  170
2012-12-07 10:02:00           3                  280
2012-12-07 10:03:00           1                  40
2012-12-07 11:16:00           1                  65  #the next hour!

我使用以下查询来获取自上午10点以来的捐款总额。但是我想按分钟将它们分组给我上面的结果例子。

SELECT SUM(donation_amount) 
FROM `DONATION` 
WHERE `time_inserted` > '2012-12-07 10:00:00' 
AND `donation_type` = 'em1';
Returns: 807,563 # the total sum of donations since 10am today.

4 个答案:

答案 0 :(得分:5)

SELECT 
  SUM(donation_amount) AS total_donation_amount,
  EXTRACT(YEAR from time_inserted) AS year,
  EXTRACT(MONTH from time_inserted) AS month,
  EXTRACT(DAY from time_inserted) AS day,
  EXTRACT(HOUR from time_inserted) AS hour,
  EXTRACT(MINUTE from time_inserted) AS minute
FROM `DONATION`
WHERE `time_inserted` > '2012-12-07 10:00:00' 
AND `donation_type` = 'em1'
GROUP BY year, month, day, hour, minute;

答案 1 :(得分:4)

怎么样:

SELECT sum(donation_amount), DATE_FORMAT(time_inserted, '%Y-%m-%d %H-%i') as dates, time_inserted FROM `donation`
group by dates
order by dates asc

答案 2 :(得分:2)

试试这个:

SELECT IFNULL(donation_type, 'Total') donation_type, 
       DATE_FORMAT(time_inserted, '%Y-%m-%d %H-%i') insertTime, 
       SUM(donation_amount), 
       COUNT(donation_type)
FROM `DONATION` 
WHERE `donation_type` = 'em1' 
GROUP BY insertTime WITH ROLLUP;

答案 3 :(得分:1)

SELECT 
    count(donation_amount) as T_Count,
    sum(donation_amount) as `Sum`
FROM
    donation
GROUP BY 
    time

由于每次都不同,所以这将获取结果OK。