Similar to my question yesterday:
I have a database table 'sales_list'. In this is rows of sales records attributed to a users_sales_guild_id. I'd like to query the table and order results by the SUM of the 'sales_points' field by each user, highest points to lowest.
I found another question on SO that I thought would solve my issue - MySQL: how to sum up vaues of rows and sort the result? - but it doesn't seem to hit the mark entirely.
I thought this query would do it, but alas no...
$total_query = "SELECT users_sales_guild_new_id, SUM(sales_points) AS total_sales_points
FROM sales_list
WHERE sales_entry_date BETWEEN '2013-10-01 00:00:00' AND '2013-12-31 23:59:59'
GROUP BY users_sales_guild_new_id
ORDER BY total_sales_points DESC";
This query returns only 1 record. rather than a selection of records ordered by the SUM of sales points by each user.
Your assistance is much welcomed.
Try this-> You can't pass the alias to order by.
$total_query = "SELECT users_sales_guild_new_id, SUM(sales_points) AS total_sales_points
FROM sales_list
WHERE sales_entry_date BETWEEN '2013-10-01 00:00:00' AND '2013-12-31 23:59:59'
GROUP BY users_sales_guild_new_id
ORDER BY SUM(sales_points) DESC";
Related
Summarize the Problem:
I cannot get ORDER BY DESC to work.
The column that I'm trying to order is DATETIME so I should not have to do a conversion, I don't think.
Describe what you've tried:
The NULL value is the one I want to fill in with the most recent datetime from a different table
Table Image. I am able to fill in a time, but the time is not the most recent pilot_death for this pilotID #. I am not able to do ORDER BY on the datetime.
Note: Since this is complicated enough for me, I have provided the data tables in an sql query in the mediafire link here: https://www.mediafire.com/file/owucp67djcc8djp/pilot_stats.sql/file
fiddle.
Before:
Code:
$sql = 'UPDATE pe_DeathAncestoryFinal
SET pe_DeathAncestoryFinal_lastpilotdeathtime = (
SELECT DISTINCT pe_LogEvent_datetime
FROM pe_LogEvent
WHERE pe_DeathAncestoryFinal_pilotid = pe_LogEvent_pilotid AND pe_LogEvent_type =
"pilot_death"
GROUP BY pe_DeathAncestoryFinal_pilotname
ORDER BY pe_LogEvent_datetime DESC )
WHERE pe_DeathAncestoryFinal_lastpilotdeathtime IS NULL
';
After: I want this date in there -> 2021-04-10 19:36:02
UPDATE pe_deathancestoryfinal
JOIN ( SELECT pe_LogEvent_pilotid,
MAX(pe_LogEvent_datetime) pe_LogEvent_datetime
FROM pe_logevent
WHERE pe_LogEvent_type = "pilot_death"
GROUP BY pe_LogEvent_pilotid ) x ON pe_DeathAncestoryFinal_pilotid = pe_LogEvent_pilotid
SET pe_DeathAncestoryFinal_lastpilotdeathtime = pe_LogEvent_datetime
WHERE pe_DeathAncestoryFinal_lastpilotdeathtime IS NULL
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=f4866412b4d46b6ec120fbd0b70939ce
I have been struggling to set this up for months and months!
I need help with setting rank to my database.
This is how my current code looks like:
$db->queryNoReturn("SET #a:=0");
return $db->query("
SELECT * FROM
(SELECT
`FFA_Stats`.`id`,
`FFA_Stats`.`player_uuid`,
`FFA_Stats`.`points`,
`FFA_Stats`.`hits`,
`FFA_Stats`.`shots`,
`FFA_Stats`.`wins`,
`FFA_Stats`.`tkills`,
`FFA_Stats`.`tdeaths`,
(`FFA_Stats`.`tkills`/`FFA_Stats`.`tdeaths`) as `KDR`,
`player`.`name`,
`player`.`uuid`,
`player`.`online`,
(#a:=#a+1) AS rank
FROM `FFA_Stats`
INNER JOIN `player` ON `FFA_Stats`.`player_uuid`=`player`.`uuid`
ORDER BY `points` DESC
) AS `sub`
");
Basically its sorting it by points and you can check how it looks like here: http://filipvlaisavljevic.com/clash/ffa.php
All I want to do is add rank to the sorted table so the player with the most points would be #1 etc.
Does anyone know what to do?
Usually a rank number would be an integer that you could generate from iterating through the rows of the query result. eg. echo $count++;
If you have calculated or attributed a rank in your database then you can add 'order by' statements separated by commas. eg.
FROM `FFA_Stats`
INNER JOIN `player`
ON `FFA_Stats`.`player_uuid`=`player`.`uuid`
ORDER BY `rank` DESC, `points` DESC) AS `sub`
");
I would like to get number of all records and get last record :
$sql_count_sms = "SELECT count(*) as total,content,id FROM android_users_sms WHERE user_id=$id ORDER BY id DESC";
$result_count_sms = mysql_query($sql_count_sms);
$row_num_sms = mysql_fetch_assoc($result_count_sms);
$num_sms = $row_num_sms['total'];
$last_my_sms = $row_num_sms['content'];
I can get number of records but I can't get last content record .
It returns first record !
Where is my wrong ?
Below codes works fine, but I think count(*) is faster than mysql_num_rows .
$sql_count_sms = "SELECT content,id FROM android_users_sms WHERE user_id=$id ORDER BY id DESC";
$result_count_sms = mysql_query($sql_count_sms);
$row_num_sms = mysql_fetch_assoc($result_count_sms);
$num_sms = mysql_num_rows($result_count_sms);
$last_my_sms = $row_num_sms['content'];
Any solution?
The grain of the two results you want is not the same. Without using a sub-query you can't combine an aggregate and a single row into the same result.
Think of the grain as the base unit of the result. The use of GROUP BY and aggregate functions can influence that "grain"... one result row per row on table, or is it grouped by user_id etc... Think of an aggregate function as a form of grouping.
You could break it out into two separate statements:
SELECT count(*) as total FROM android_users_sms WHERE user_id = :id;
SELECT * FROM android_users_sms WHERE user_id = :id ORDER BY id DESC LIMIT 1;
Also, specific to your question, you probably want a LIMIT 1 in combination with the ORDER BY to get just the last row.
Now, counter intuitively perhaps, this should also work:
SELECT count(*), content, id
FROM android_users_sms
WHERE user_id = :id
GROUP BY id, content
ORDER BY id
LIMIT 1;`
This is because we've changed the "grain" with the GROUP BY. This is the real nuance and I feel like this could probably be explained better than I am doing now.
You could also do this with a sub query like so:
SELECT aus.*,
(SELECT count(*) as total FROM android_users_sms WHERE user_id = :id) AS s1
FROM android_users_sms AS aus
WHERE user_id = :id ORDER BY id DESC LIMIT 1;
I am working on a project to build an assessment leader board for a learning centre. I've got a table that looks like this
I am trying to write a query which will select all from the table by CLASS, within DATE range, add score per individual STUDENT_ID and then order in descending order by the added score to create the leader board. I've read a little on sub queries but can't quite understand the examples or exactly how they work, I also think I would need a SELECT DISTINCT student_id in my query but my knowledge here is also limited as I have only used it once.
Anyway this is what I have so far.
$classcheck = mysql_query("SELECT *
FROM assessment
WHERE class = '$class_info'
order by score DESC")
or die(mysql_error());
if(mysql_num_rows($classcheck) > 0){
while($row = mysql_fetch_array($classcheck)){
if(strtotime($row["date"]) > strtotime($fromdate) && strtotime($row["date"]) < strtotime($todate)){
echo $row['score'].'<p>';
}
}
}
But I need it to add SCORE and order by the added SCORE in the query somewhere which I cannot achieve with what I have written.
I know should start using PDO rather than mysql_query, knowledge limited again and I am running out of time. All feedback would be greatly appreciated. OH, and the score is really a percentage.
You don't need a subquery, you just need SUM and GROUP BY to total the scores by student, and a WHERE clause to restrict the dates.
SELECT student_name, SUM(score) AS total_score
FROM assessment
WHERE date BETWEEN '$fromdate' AND '$todate'
AND class = '$class_info'
GROUP BY student_id
ORDER BY total_score DESC
I think a GROUP BY might do the trick since you are trying to add up all the scores of an individual STUDENT_ID.
Please feel free to correct me if I'm wrong but the following SQL should get you what you are looking for.
SELECT SUM(score) AS ttl_score, student_name
FROM assessment
WHERE class='$class_info'
AND date>='$start' AND date<='$end'
GROUP BY student_id ORDER BY ttl_score DESC;
$classcheck = mysql_query("Select Student_id, sum(Score) as SummedScore from assessment where class='$class_info' and
date between '$fromdate' and '$todate' Group by Student_ID Order By SummedScore"
or die(mysql_error());
if(mysql_num_rows($classcheck) > 0){
while($row = mysql_fetch_array($classcheck)){
echo $row['SummedScore'].'<p>';}
}
I have a database table 'sales_list'. In this is rows of sales records attributed to a users_sales_guild_id. I'd like to query the table and order results by the number of sales made by each user, highest to lowest.
I thought this query would do it, but alas no...
$total_query = "SELECT *, COUNT(users_sales_guild_id) AS users_sales_guild_id_count FROM sales_list WHERE sales_entry_date BETWEEN '2013-10-01 00:00:00' AND '2014-11-30 23:59:59' ORDER BY users_sales_guild_id_count DESC";
$total_rs = mysql_query($total_query) or trigger_error ("Query: $total_query\n<br>MySQL Error: " .#mysql_error()); // Run the query.
$num_rs = mysql_num_rows($total_rs);
This query returns 1 record. rather than a selection of records ordered by the number of sales by each user.
Your assistance is much welcomed.
count(*) will return one row unless there is a group by clause, so the query should be as
SELECT *,
COUNT(*) AS users_sales_guild_id_count
FROM sales_list
WHERE sales_entry_date BETWEEN '2013-10-01 00:00:00' AND '2014-11-30 23:59:59'
group by users_sales_guild_id
ORDER BY users_sales_guild_id_count DESC
UPDATE : Its better to select col1,col2 ..... instead of * while doing group by - Point raised by InoSHeo
check this link
http://sqlfiddle.com/#!2/1201d/6
check this link if you would like to get details based on username http://sqlfiddle.com/#!2/1201d/4 here i have used type instead you can use username