Get the last entries using GROUP BY - mysql

I'm having problem with GROUP BY. It returns the first entry it could find, but I would like it to return the last entry. Is that possible?
Here is my query (prepared query):
SELECT stamp_user, stamp_date, stamp_type
FROM rws_stamps
WHERE stamp_date >= ?
GROUP BY stamp_user
ORDER BY stamp_date DESC
My table looks like this:
What I want it to return is row 7 and 3, but i get 1 and 2.

Try:
SELECT stamp_user, max(stamp_date), stamp_type
FROM rws_stamps
WHERE stamp_date >= ?
GROUP BY stamp_user, stamp_type

Related

MySQL checking last updated time on multiple devices

I would like to check the last update date and time (recordTime) for every treehugger id (TreeHuggerId) and below is what I did. The output was not the last update time according to the below query. Please advice. Thank you.
SELECT `recordTime`, DISTINCT `TreeHuggerId` FROM `SENSOR_TREEHUGGERS`
WHERE `TreeHuggerId` < 20000 and `TreeHuggerId` > 10000
ORDER BY `recordTime` desc
You have to select MAX(recordTime) for every TreeHuggerId for that and you don't need distinct
SELECT TreeHuggerId,MAX(recordTime) FROM SENSOR_TREEHUGGERS
Then at the end
GROUP BY TreeHuggerId
Like this
SELECT TreeHuggerId,MAX(recordTime) FROM SENSOR_TREEHUGGERS
WHERE TreeHuggerId BETWEEN 10000 AND 20000
GROUP BY TreeHuggerId

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...

mysql select with priority of 3 filelds in a query

my table and fields are like these:
i must find $sy<year<$ey then it must filter only values by $sm<month<$em at last it must find $sd<day<$ed
i need to find records between dates for example like 2010/10/25 , 2010/10/10
at first i tried :
SELECT SUM(barname) allin,SUM(rooz) allhoghogh,user_id FROM work_result
WHERE (`year`>='$sy' and `month`>='$sm' and `day`>='$sd') and (`year`<='$ey' and `month`<='$em' and `day`<='$ed') group by user_id ;
but it cant find records for dates like e like 2010/10/25 , 2010/10/28
than i tried
SELECT * FROM work_result as t1 join work_result as t2 on t1.year<='$sy' and t2.year>='$ey' and t1.month<='$em' and t2.month>='$sm' and t1.day<='$ed' and t2.day>='$sd' WHERE 1 group by t1.wrid
this isnt usful in my case!
i need some thing like priority select first select all between years than month and than day!!
other way is convert mysql records to timestamp by year and month and day and compare it by input date but UNIX_TIMESTAMP('year-month-day 00:00:00') dont worked correct for me.
i used it like :
SELECT * FROM `work_result` WHERE UNIX_TIMESTAMP('year-month-day 00:00:00')>1238921453
If convert to timestamp didn't work for you what about use date_format to convert:
SELECT *
FROM `work_result`
WHERE date_format(concat(year,'-',month,'-',day), '%Y-%m-%d') >
DATE_FORMAT(FROM_UNIXTIME(`yourDateGoesHere`), '%Y-%m-%d')

GROUP BY ORDER BY Help

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

A specific value(only one) to be first in a query result. Rest order by time stamp

I have a search result query for posts. And I want posts written by myself(userId = 27) to be first in query result and rest ordered by time stamp. Can anyone give me query for that in mysql?
select *
from posts
order by
if (userid=27, -1, any_timestamp_include_zero);
include your full table schema help much better
How about something like:
select * from post
order by
case
when userid = 25 then '0001-01-01 00:00:00'
else my_timestamp
end
(formatting the '0001-01-01' part appropriately for MySql)
Something simple like this:
SELECT * FROM POST WHERE userId = 25
UNION
SELECT * FROM POST WHERE userId <> 25 ORDER BY TIMESTAMP_FIELD
Could work for your need?