简体   繁体   中英

Mysql Count number of Rows Depending on Date

Well, I don't know what title it should be nor how can I explain it, but I'll do my best to explain my problem.

I have this table consists of certain data that focuses on date_participated and fblike_point .

在此输入图像描述

Well, my desired output should be

2013-03-20 1

2013-03-19 3

So basically, each date will count the number of fblike_point .

On 2013-03-19 it has total of 3 fblike_point and on 2013-03-20 it has a total of 1 fblike_point

and my problem is, I'm outputting not my desired results, I'm getting a result of 2013-03-19 4

It stays in 1 date and counts the number of fblike_point

Here is my code for that.

$query = "SELECT DISTINCT date_participated, COUNT(fblike_point) as fblike FROM event_raffles WHERE ticket_id='". $ticket_id ."' AND event_table='". $event_table ."' AND status='1' ORDER BY date_participated DESC";
$result = db_query($query);

foreach ($result as $values) {
    echo $values->date_participated . " " . $values->fblike . "<br>";
}

Any solutions for this stuff? Any help would be appreciated. :)

You should alter your query to use a GROUP BY instead of the DISTINCT

SELECT date_participated, COUNT(fblike_point) as fblike 
FROM event_raffles
GROUP BY date_participated

The way you've used DISTINCT is to get all unique dates and for each result, add the amount of records returned in the entire resultset.

Using a GROUP BY allows you to use any aggregate function available on that group .


Edit

As been mentioned by @ysth, instead of using COUNT you might want to use SUM depending on the possible values that fblike_point can have.

Using SUM would actually be the more sensible course of action.

use below query by removing DISTINCT and replacing ORDER BY to GROUP BY

$query = "SELECT date_participated, COUNT(fblike_point) as fblike FROM event_raffles WHERE ticket_id='". $ticket_id ."' AND event_table='". $event_table ."' 
AND status='1' GROUP BY date_participated DESC";

Replace

$query = "SELECT DISTINCT date_participated, COUNT(fblike_point) as fblike FROM event_raffles WHERE ticket_id='". $ticket_id ."' AND event_table='". $event_table ."' AND status='1' ORDER BY date_participated DESC";

with

$query = "SELECT  date_participated, COUNT(fblike_point) as fblike FROM event_raffles WHERE ticket_id='". $ticket_id ."' AND event_table='". $event_table ."' AND status='1' GROUP BY date_participated ORDER BY date_participated DESC";

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