Group together by date, but show all rows - php

Normally when I group stuff together it is for the obvious use to group together duplicates, but I am making a winners page that shows winners for a bunch of jackpots, some jackpots have 1 winner while other have 3, using GROUP BY date will work if there is only 1 winner but will only show 1 winner when there should be 3.
Here is my code
$result = $db->query("SELECT * FROM r_winners GROUP BY date ORDER BY date DESC");
while($rows = $result->fetch_assoc()){
print"<table class='cashout' style='width:100%;'>
<th colspan='3'>".$rows['jackpot_name']." Winners</th>
<tr>
<td style='width:33%;'>".$rows['winner']."</td><td style='width:33%;'>$".$rows['amount']."</td><td style='width:33%;'>".date("m/d/Y", $rows['date'])."</td></tr>
</tr></table>";
}
It prints out a table like such
---------------------------------------
Daily Jackpot Winners
Username| $5.00 | 12/5/2012 // This table is right, because there is only 1 winner
---------------------------------------
Because there is only 1 winner then GROUP BY really has no affect here
Here is a table for multiple winners
---------------------------------------
Monthly Jackpot Winners
Username | $5.00 | 12/5/2012 // This table is wrong, because there should be 3 winners
---------------------------------------
It needs to look like this
---------------------------------------
Monthly Jackpot Winners
Username | $5.00 | 12/5/2012
Username2 | $2.00 | 12/5/2012
Username3 | $1.00 | 12/5/2012
---------------------------------------
How can I accomplish this?
EDIT: This can maybe explain this better https://gist.github.com/4221167

Just don't use GROUP BY at all. You are already using ORDER BY which will put your dates into logical "groupings".
In response to your comments about ho to output the results in one table, here is how you would need to modify your code.
$result = $db->query("SELECT * FROM r_winners ORDER BY date DESC");
print "<table class='cashout' style='width:100%;'>";
print "<th colspan='3'>".$rows['jackpot_name']." Winners</th>";
while($rows = $result->fetch_assoc()){
print "<tr><td style='width:33%;'>".$rows['winner']."</td><td style='width:33%;'>$".$rows['amount']."</td><td style='width:33%;'>".date("m/d/Y", $rows['date'])."</td></tr>";
}
print "</table>";

Change your query to just use ORDER BY and reformat your loop, placing the table elements outside, and only printing the header once
$result = $db->query("SELECT * FROM r_winners ORDER BY date DESC");
print"<table class='cashout' style='width:100%;'>";
$jackpot_name = '';
while($rows = $result->fetch_assoc()){
if ($jackpot_name != $rows['jackpot_name']) {
$jackpot_name = $rows['jackpot_name'];
print "<th colspan='3'>".$rows['jackpot_name']." Winners</th>";
}
print "<tr><td style='width:33%;'>".$rows['winner']."</td><td style='width:33%;'>$".$rows['amount']."</td><td style='width:33%;'>".date("m/d/Y", $rows['date'])."</td></tr>";
}
print "</table>";

Try removing the GROUP BY and only using ORDER BY.

You should GROUP BY Monthly ORDER BY Winners, of course, if Monthly is unique, then you even don't need to GROUP BY it.
Edit:
After checking your php code, I think you need below:
SELECT
GROUP_CONCAT(winner_name) AS winner_names,
SUM(the_value_column_you_want_to_sum) AS amount
FROM r_winners
GROUP BY date ORDER BY date DESC

Related

Codeigniter count using month?

The scenario is I am the admin and I have a session to make, the session table consists of a session_id, coach_name, date(format Y-m-d).
Now I want to count the total activity of the coach every "MONTH".
So my point is how will I get this kind of output in a SQL query.
The desired output is the amount of activity per month, per coach.
Name | No. of session this month
Coach_name1 = 13
Coach_name2 = 5
This is my current query that gives me the coach name but I don't know how to get for each MONTH
public function getAll(){
$query = $this->db->query('SELECT DISTINCT coach_name FROM sessions);
return $query->result();
}
Use this query to get the result.
Use mysql MONTH() to get Month number from date and group by it. You will get all month wise data.
SELECT coach_name,
Count(*) AS activities
FROM sessions
WHERE Month(date) = 8 //for specfic month
GROUP BY coach_name, Month(date) // for all months
Use this query to dynamincally get current month based on system date
SELECT coach_name,
Count(*) AS activities
FROM sessions
WHERE Month(date) = MONTH(CURRENT_DATE()) //for selecting current month.
GROUP BY coach_name
You have to prepare query like below:
select
coach_name,
month(your_date_field),
count(1)
from
your_table
where
month(your_date_field) = 8
group by
coach_name, month(your_date_field)
Which would return records like below,
| coach_name | month(your_date_field) | count(1) |
+---------------+------------------------+------------+
| Coach_name1 | 8 | x |
| Coach_name2 | 8 | x |
| Coach_name3 | 8 | x |
+---------------+------------------------+------------+
In codeigniter
$this->db->select("coach_name, month(your_date_field) as month_number,count(1) as counts");
$this->db->where('month(your_date_field)',8);
$this->db->group_by('coach_name,MONTH(your_date_field)');
$query = $this->db->get('your_table');
// results
foreach ($query->result_array() as $row)
{
// do this to see array
print_r($row);
// to access individual fields
echo $row['coach_name'];
echo $row['month_number'];
echo $row['counts'];
}
Use MySQL's MONTH() in your query. So basically if all your data is in your sessions table try the following in your query.
SELECT DISTINCT(`name`),COUNT(`name`) AS `activity` FROM `session`
WHERE MONTH(`date`)=8 GROUP BY `name`;
Check in SQLFiddle

Selecting max percentage from the column for every subject

I have table called skills in which different skills are stored for that particular user in % so basically i want to select highest skills for that user from skills table and want to echo it in while loop for every user
user | skills |
userID | PHP |
userName | C++ |
<?php
$sql= "(SELECT *,max(skills) as higherPercentage
FROM skill LEFT JOIN user ON skill.userID=user.userID ORDER BY signup_date DESC ) ";
$res = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($res)) {
?>
So If the user has Highest vale 99 compare to all the skills then it should be selected for him
Store values in like 1,0.5,6 not like 100%,10%
and then use
SELECT MAX(column_name) FROM table_name group by (user)

How to set variable from MAX and group?

I have problem with selecting selecting SQL Max and group syntax then set it to variable. I have no problem from just selecting the MAX score. But Id like to echo the user that own that score and id to redirect to his profile page
This is my Database
-----------------------------
id | user | score | justplayed
1 | player1 | 1000 | 1
2 | player2 | 1000 | 0
PHP code
$sql = "SELECT MAX(score) AS max_score FROM score GROUP BY score WHERE justplayed > 0 ";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$highscore = $row["max_score"];
$highscoreowner = $row["user"];
$highscoreownerid = $row["id"];
}
}
Html Code
Player of the day
<? echo $highscoreowner; ?>
Score
<? echo $highscore; ?><br>
<a href="profile.php?id=<? echo $highscoreownerid; ?>
You're only selecting the max score in the SQL query, so you can't extract the other values in PHP. If you're looking for the entire row where the score is highest, then use this query instead:
SELECT score, user, id
FROM score
WHERE justplayed > 0
ORDER BY score DESC
LIMIT 1
This will take all the rows, order them from highest to lowest score, and then return only the first row.

How To select last inserted Row in PHP , Mysql

I m trying to create ID like "A1 , A2, A3 .. etc
So i tried like this
$q = mysql_query("SELECT merge_id FROM merge_info ORDER BY merge_id DESC LIMIT 1;");
$s = mysql_fetch_array($q);
$merge_id5 = $s['merge_id'];
$count2=mysql_num_rows($q);
if($count2>0)
{
$merge_id5 = explode("A",$merge_id5);
$mergeid_no = $merge_id5[1]+1;
$merge_id6 = $mergeid_no;
}
else
{
$merge_id6 ="1";
}
if($count<1)
{
$merge_id = $merge_id5;
}
Everything is working fine... but after creating A9, it create A10 then again it creates A10 not moving to A11 , A12 . etc., i think if i write correct query to fetch last inserted row i'll fix this issue
Please someone help me
db table :
merge_id | name |
A1 | xxxx |
A2 | yyyy |
A3 | zzzz |
....
....
A9 | sds |
A10 | dsfs |
i know it is not the best solution to your problem, but this will help you.
and just get the first record because if i add LIMIT 1 the output is wrong :(
SELECT * FROM merge_info ORDER BY LENGTH(merge_id) DESC
Change your query to:-
SELECT MAX(merge_id) FROM merge_info;
I think it's better you use an auto_increment field, to get the last insert row with LAST_INSERT_ID(), otherwise you can't be sure if the last row, the one you have inserted.
So long. To order with your solution, use this.
ORDER BY SUBSTRING(merge_id,2) DESC
Better approach to your problem could be ,
use AUTO_INCREMENT field and while displaying append 'A' to it.
Now to solve this you can use below SQL statement
SELECT * FROM `merge_info` ORDER BY SUBSTRING(merge_id,2) DESC limit 1
should change you merge_id column into auto increment column,and the change your query into below mentioned,
SELECT MAX(merge_id) FROM merge_info;
if you want id like A1,A2,A3 ... then you can use the below code for get it
$q = mysql_query("SELECT merge_id FROM merge_info ORDER BY merge_id DESC LIMIT 1;");
$s = mysql_fetch_array($q);
$merge_id5 = $s['merge_id'];
$count2=mysql_num_rows($q);
$merge_id="A".$merge_id5;
after above process,noe we have a meger_id like A1,A2.. on application side

PHP/MySQL - Ranking based on last db column

I’ve two tables (MySQL): player and scores. In scores table are stored annual scores in this way:
player_id | 2002 | 2003 | 2004
1 | 5 | 6 | 4
2 | 3 | 2 | 5
Etc.
I write the follow code to make a ranking based on last year scores.
$extract = mysql_query("SELECT * FROM players AS p, scores AS s WHERE p.player_id =s.player_id ORDER BY s.2004 desc");
while ($row = mysql_fetch_assoc($extract)) {
$name = $row['name'];
$score = $row['2004'];
if ($row['2004'] < $row['2003']) {
$value = "-";
}
else if ($row['2004'] > $row['2003']) {
$value = "+";
}
else if ($row['2004'] == $row['2003']) {
$value = "=";
}
echo "<b>".$name."</b> | ".$score." ".$value."<br>\n";
}
But this code has two big problems:
1) In the query I have to specify the last year (ORDER BY s.2004), so if I add another column (eg. 2005) into scores table, I have to manually change the code.
2) Same thing for the “$value” var. If I add 2005, the comparison between 2004 and 2003 becomes wrong (it should be between 2005 and 2004).
I know I have to use loops and array but... how?
You should redesign your scores table to store player_id, score and year in one row. So, each score gets its own row. When you find yourself duplicating columns, you are usually heading in the wrong direction.
Then, your query would look like:
Select Year(CURDATE());
select *
from players p
inner join scores s on p.player_id = s.player_id
where s.`Year` = Year(CURDATE()) --or (select max(Year) from Score)

Categories