GROUP BY ORDER BY Help - mysql

The following code works, but I want the groups to show their latest query by datetime not the first datetime query. I've tried changing around the ORDER BY from ASC/DESC, but that just changes the order of all the groups, not the data within the groups. I need for both all the inside data of the groups and all the groups to order by the latest datetime.
$query="SELECT * FROM emails
WHERE sentto='$sid'
GROUP BY sentto
ORDER BY datetime DESC LIMIT $eu, $limit ";
Instead of it showing groups and ordering them by the first query:
Message from Sam Richards on January 22, 2011 (this is a group)
Message from John Smith on January 5, 2011 (this is a group)
I want it to show groups and order them by the latest query:
Message from John Smith on April 19, 2011 (this is a group)
Message from Sam Richards on March 10, 2011 (this is a group)
Please help.

I think part of your problem is that you are selecting non-aggregate columns with a group-by query. You should be explicit about which values you want it to return in the aggregate query result.
SELECT sentto, MAX(datetime) AS datetime FROM emails
GROUP BY sentto
ORDER BY datetime desc LIMIT $eu, $limit;
I'm still not sure that this gives you what you want. It sounds like you want to actually retrieve the rows for each individual email and just use the GROUP BY maximum for sorting. To do that, you'd probably need to do the above query, then go back and do a second query for each sentto. I can't think of a way offhand to do it in a single query.
SELECT * FROM emails
WHERE sentto=$sid
ORDER BY datetime DESC;
(For each sentto returned in the first query.)

How about:
ORDER BY sentto ASC, datetime DESC

To sort the data with in the groups you need to include sentto in the ORDER BY clause.
Try this:
SELECT * FROM emails
WHERE sentto='$sid'
GROUP BY sentto
ORDER BY sentto, datetime DESC LIMIT $eu, $limit

Related

SQL sum(time) as time column does not sort in ASC and DESC order

I have been trying to sort the result of my SQL query but it's not working properly,
I have tried other solutions, but not worked, reference link
My Query
SELECT tournament_entry.TE_club, MAX(tournament_entry.TE_pegion) As TE_pegion,
concat(
floor(SUM(TIME_TO_SEC(tournament_entry.TE_flytime))/3600),':',
floor(SUM( TIME_TO_SEC(tournament_entry.TE_flytime))/60)%60,':',
SUM(TIME_TO_SEC(tournament_entry.TE_flytime))%60) as TE_flytime
FROM tournament_entry
WHERE tournament_entry.TE_tournament = '$Tname'
GROUP BY TE_club
ORDER BY TE_flytime DESC
Point 1, I have used CONCAT(), the reason to display the sum of time greater than 838:59:59 reference link
Step 1 followed,
ORDER BY TE_flytime ASC
results, which is not correct
Step 2 followed,
ORDER BY TE_flytime DESC
results, not correct, in this way it takes results greater than 1000 to the bottom (last),
maybe if there is any logic or way to use and it will sort it properly.
Step 3 followed,
ORDER BY 'cast(TE_flytime as float) time'
results, not correct, mixed up all results. reference link
NOTE: I want to sort it in a way that it displays the greatest result on top and so on
e.g
1034:46:0
1027:4:0
965:37:0
809:11:0
The calculated column TE_flytime is a string so if you sort by that column the sorting will be alphabetical.
You can order by the total number of seconds:
ORDER BY SUM(TIME_TO_SEC(tournament_entry.TE_flytime)) DESC

SQL: How do I search the data with the LATEST date AND the MOST value in quantity_used?

I know how to search the LATEST date and the MOST value specifically:
Most Quantity Used:
SELECT * FROM tour_packages
WHERE active = 1
ORDER BY quantity_used DESC
Latest Date:
SELECT * FROM tour_packages
WHERE active = 1
ORDER BY start_date DESC
But how can I do both, by able to search the LATEST date WITH the MOST value in quantity_used? Is this practice even possible?
EDITED: I think my question is not clear enough.
I intend to find the data with the LATEST date first, then from that result FIND the highest VALUE from quantity_used.
I think you just want two order by keys:
SELECT tp.*
FROM tour_packages tp
WHERE tp.active = 1
ORDER BY tp.start_date DESC, tp.quantity_used DESC;
This returns the rows ordered by date and within each date, the ones with the largest quantity go first.

Count per month if unique

I am trying to get a SQL query to count personid unique for the month, is a 'Returning' visitor unless they have a record of 'New' for the month as well.
month | personid | visitstat
---------------------------------
January john new
January john returning
January Bill returning
So the query I'm looking for should get a count for each unique personid that has "returning" unless a "new" exists for that personid as well - in this instance returning a count of 1 for
January Bill returning
because john is new for the month.
The query I've tried is
SELECT COUNT(distinct personid) as count FROM visit_info WHERE visitstat = 'Returning' GROUP BY MONTH(date) ORDER BY date
Unfortunately this counts "Returning" even if a "New" record exists for the person in that month.
Thanks in advance, hopefully I explained this clearly enough.
SQL Database Image
Chart of Data
You already wrote the "magic" word yourself, "exists". You can use exactly that, a NOT EXISTS and a correlated subquery.
SELECT count(DISTINCT vi1.personid) count
FROM visit_info vi1
WHERE vi1.visitstat = 'Returning'
AND NOT EXISTS (SELECT *
FROM visit_info vi2
WHERE vi2.personid = vi1.personid
AND year(vi2.date) = year(vi1.date)
AND month(vi2.date) = month(vi1.date)
AND vi2.visitstat = 'New')
GROUP BY year(vi1.date),
month(vi1.date)
ORDER BY year(vi1.date),
month(vi1.date);
I also recommend to include the year in the GROUP BY expression, as you otherwise might get unexpected results when the data spans more than one year. Also only use expressions included in the GROUP BY clause or passed to an aggregation function in the ORDER BY clause. MySQL, as opposed to virtually any other DBMS, might accept it otherwise, but may also produce weird results.
I also faced one of the same scenarios I was dealing with a database. The possible way I did was to use group by with having clause and a subquery.

SELECT SUM not limiting as requested

I'm totally new to the land of databases. I'm wanting to get the total of more than one column from my database so am doing this... (below). The problem is, when it is returning the total for each column it isn't limiting it to the last 7 rows by date. It's returning the total for that consultant.
$result = mysql_query("SELECT SUM(NewPermJobs) AS NewPermJobsTotal,
SUM(CandidatesSubmitted) AS CandidatesSubmittedTotal, SUM(FirstInterviewsRecorded)
AS FirstInterviewsRecordedTotal, SUM(OldJobsReactivated) AS OldJobsReactivatedTotal,
SUM(CandidateRecordsUpdated) AS CandidateRecordsUpdatedTotal, SUM(CompaniesAddedDream)
AS CompaniesAddedDreamTotal, SUM(SocialContentShared) AS SocialContentSharedTotal,
SUM(ApplicantStatusChanged) AS ApplicantStatusChangedTotal, SUM(JobsClosed) AS
JobsClosedTotal, SUM(Revenue) AS RevenueTotal FROM dailyactivity WHERE (`Consultant`
LIKE '%".$query."%') ORDER BY Date DESC LIMIT 0,7");?>
It's probably really messy but is the best I can put up at this stage. Any idea why it isn't limiting the sum of the columns to the last 7 ordered by date desc?
Any help would be amazing!
You can first limit the results using a subquery and then do the sum, like this:
SELECT SUM(NewPermJobs) AS NewPermJobsTotal,
SUM(CandidatesSubmitted) AS CandidatesSubmittedTotal,
SUM(FirstInterviewsRecorded) AS FirstInterviewsRecordedTotal,
SUM(OldJobsReactivated) AS OldJobsReactivatedTotal,
SUM(CandidateRecordsUpdated) AS CandidateRecordsUpdatedTotal,
SUM(CompaniesAddedDream) AS CompaniesAddedDreamTotal,
SUM(SocialContentShared) AS SocialContentSharedTotal,
SUM(ApplicantStatusChanged) AS ApplicantStatusChangedTotal,
SUM(JobsClosed) AS JobsClosedTotal,
SUM(Revenue) AS RevenueTotal
FROM (
SELECT NewPermJobs, CandidatesSubmitted, FirstInterviewsRecorded,
OldJobsReactivated, CandidateRecordsUpdated, CompaniesAddedDream,
SocialContentShared, ApplicantStatusChanged, JobsClosed, Revenue
FROM dailyactivity
WHERE (`Consultant` LIKE '%".$query."%')
ORDER BY Date DESC
LIMIT 0,7
) t
$result = mysql_query("SELECT SUM(NewPermJobs) AS NewPermJobsTotal,
SUM(CandidatesSubmitted) AS CandidatesSubmittedTotal, SUM(FirstInterviewsRecorded)
AS FirstInterviewsRecordedTotal, SUM(OldJobsReactivated) AS OldJobsReactivatedTotal,
SUM(CandidateRecordsUpdated) AS CandidateRecordsUpdatedTotal, SUM(CompaniesAddedDream)
AS CompaniesAddedDreamTotal, SUM(SocialContentShared) AS SocialContentSharedTotal,
SUM(ApplicantStatusChanged) AS ApplicantStatusChangedTotal, SUM(JobsClosed) AS
JobsClosedTotal, SUM(Revenue) AS RevenueTotal FROM dailyactivity WHERE (`Consultant`
LIKE '%".$query."%') group by 'required_column_name' ORDER BY Date DESC LIMIT 0,7");?>
Use the group by .... It will solve your problem...

Missing records when ordering rows by date

This would be my query:
SELECT * FROM Bans ORDER BY Date DESC LIMIT 10
Here's how the timestamp(Date) looks: September 01, 2012 - 10:33:13 | May 31, 2012 - 19:28:25, etc.. Now, my problem is, is that I have records from June, but they aren't showing.
How can I fix this?
Edit: This table should show the "Latest" 10 bans.
I may supose that dates are sorted in the alphabetical order, maybe you should try
SELECT * FROM Bans ORDER BY TO_SECONDS(Date) DESC LIMIT 10
Date might be considered as a keyword in MySQL. Wrap it inside the backticks. Dates are not in the correct form. Use TO_SECONDS and alter the query this way:
SELECT * FROM `Bans` ORDER BY TO_SECONDS(`Date`) DESC LIMIT 10