SELECT SUM not limiting as requested - mysql

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

Related

Store calendar week and year in one (date) column in SQL

My table includes two columns: calendar week and year.
If I want to get the latest entries by calendar week and year, I currently perform:
SELECT * FROM table WHERE calyear = (SELECT MAX(calyear) FROM table) AND calweek = (SELECT MAX(calweek) FROM table WHERE calyear = (SELECT MAX(calyear) FROM table))
which is super long. I'd like to replace this with a combination of week and year e.g. 'calweek-calyear' column. Is there a date format for that or should I save this as a tiny text?
I want to be able to perform MAX() on it and performance shouldn't suffer singificantly.
Im open for better solutions, thanks.
Your super long query can be simplified to:
SELECT *
FROM tablename
ORDER BY calyear DESC, calweek DESC
LIMIT 1;
if you expect only 1 row as a result.
If there are more than 1 rows for the max calyear and calweek combination, you could use RANK() window function:
SELECT t.*
FROM (
SELECT *, RANK() OVER (ORDER BY calyear DESC, calweek DESC) rnk
FROM tablename
) t
WHERE t.rnk = 1;
Also, I would advice against the use of a combination of year and week.
Keep your data as simple as possible.
For presentation purposes you could easily concatenate the 2 columns.
If you concatenate YYYYWW in a column TINYTEXT, or other text type I think it will do what you want.
If you make sure that your week numbers are 2 digit ie 01 and not 1 you could use INT.
I would rather advise the use of a column DATE and a modified query.

Dealing with the count function

My Boss want to know how many times each of these shipping number of days occurred. Ordered by number of days DESC.
So far have :
SELECT DateDiff(shippedDate,orderDate) As '#Days', COUNT(*)
FROM datenumtest
I think I need condition, can someone help me out with this?
Calculate the DateDiff across all records first in a data set r, then you can do the grouping on that data set which becomes data set r1 then sort the r1 data set:
select r.NumDays, count(1) as the_count
from (
SELECT DateDiff(shippedDate,orderDate) as 'NumDays'
FROM datenumtest
) r
group by r.NumDays
order by r.NumDays desc;

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?

Get the last entries using GROUP BY

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