简体   繁体   中英

Fetching last 30 days data from mysql table and grouping them by date

Here is how my table looks like

| total_hit   |success_hit  | date_time             |
|      12     |          12 | 01-11-2009 07:32:44   | 
|      12     |          11 | 01-11-2009 08:33:49   | 
|      12     |          10 | 01-11-2009 09:08:24   | 
|      12     |          11 | 01-12-2009 10:33:57   | 
|      12     |          12 | 01-12-2009 11:37:34   | 
|      12     |          11 | 01-12-2009 12:23:49   | 

I am fetching the data from the table for the past 30 days using the following query:

SELECT *
FROM my_table
WHERE DATE(date_time) >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)

what I want to do is group the returned data in terms of date and calculate the percentage success (success_hit/total_hit)*100 Something like

Date: 01-11-2009 Percentage: x
Date: 01-12-2009 Percentage: y

any ideas?

select (success/total)*100 as perc_success, Date(date_time) from 
       (select sum(success_hit) as success, sum(total_hit) as total, 
            date_time from my_table
            where DATE(date_time) >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) 
            group by Date(date_time)  ) 
tbl

This should work!!!

Try this

SELECT (sum(success_hit)/sum(total_hit)*100) AS `Percentage`,
       DATE(date_time) AS `Date`
FROM my_table
WHERE DATE(date_time) >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)
GROUP BY DATE(date_time);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM