I want to fetch data weekwise for the particular month.
ex: if i select may month . i need count of first week,count of second week ,count of third week and so on
use the following query.
select
concat(year(date_format(timefield, '%Y-%m-%d')), ' week ', substring_index(dayofyear(date_format(timefiels, '%Y-%m-%d'))/7+1, '.', 1)) as time,
sum(sales) as sales
from
account
where
timefield>='2014-05-01 00:00:00'
and timefield<='2014-05-31 23:59:59'
group by
time;
Related
I have a table with different columns. Two of them are user and data. I want to find which users have no records in the last week.
How far have I arrived:
This gives me well the records ordered first by user and then by date:
SELECT *
FROM table1
ORDER BY user, date
I also could find a way to store one week in a var:
$oneWeek = strtotime("-1 week");
$oneWeek = date("Y-m-d H:i:s", $oneWeek);
echo $oneWeek . "<br>";
Is there a way I can select the users that do not have any records in the last seven days?
Use GROUP BY and HAVING:
SELECT t1.user
FROM table1 t1
GROUP BY t1.user
HAVING MAX(t1.date) < DATE_ADD(CURDATE(), INTERVAL -7 DAY);
This returns users whose maximum date is more than a week in the past. That is another way of saying that there are no records in the past week.
I want to have a SQL Query that selects between two dates of months.
Lets say between the 15th and the 15th of the next month.
This is for accounting purposes
I know with each month having different days adding 30 days or 31 days to the start date will not work especially in Feb. My accounting run is from the 15th of the month to the 15th of the next month.
My current query for selected dates are as follows
SELECT * FROM lbs_trace_etrack WHERE lbs_date >= '" . $dates . "'
AND lbs_date <= '" . $datee . "' AND lbs_client='$slcustom1' ORDER BY lbs_date DESC, lbs_time DESC
lbs_date start should be the 15th of each month and lbs_date end should be the 15th of the next month
By defining the dates as follow works but it is giving me from the November date to now and I want it from the 15th of this month seeing we have past the 15th of the current month already
$first = date('Y-m-15', strtotime("$last -1 month"));
$last = date('Y-m-t');
and the query
SELECT * FROM lbs_trace_etrack WHERE lbs_date >= '" .
$first . "'
AND lbs_date <= '" . $last . "' ORDER BY lbs_date DESC
Basically as we pass the current month 15th I need it to show me the current usage from the current 15th not the previous month 15th to now
If you really want what I understand you want,
SELECT l.*
FROM lbs_trace_etrack l
JOIN (SELECT s.cd, CASE
WHEN s.cd >= DATE(DATE_FORMAT(s.cd,'%Y-%m-15'))
THEN DATE(DATE_FORMAT(s.cd,'%Y-%m-15'))
ELSE DATE_SUB(DATE(DATE_FORMAT(s.cd,'%Y-%m-15')), INTERVAL 1 MONTH)
AS start_date
FROM (SELECT CURDATE() cd) s) d
ON (TRUE)
WHERE l.lbs_date >= d.start_date
AND l.lbs_date < d.cd
AND l.lbs_client = '$slcustom1'
ORDER BY l.lbs_date DESC, l.lbs_time DESC;
Please note that you still have the PHP variable $slcustom1 there.
The JOIN with subselect is motivated by the need to call CURDATE() only once, to avoid the rare occasion in which the date might change between two subsequent invocations.
Please check if comparisons <, >= etc. are what you want.
Edit:
I’ve moved the computation of start_date to the joined table. Even if in this way I have to call DATE(DATE_FORMAT()) three times, it is better than to compute DATE_SUB for every row, in the case we are in the first half of the month.
Could you able to use mysql day() function for your requirement.
Ex:
SELECT day("2016.12.15");
result:
15
Like wise you can use this function to check whether its "15"
select day(currentDate())
use DAY() function to get specific date
select * from My_Table where day(str_to_date(`Date`,'%d-%m-%Y')) = 1 or day(str_to_date(`Date`,'%d-%m-%Y')) = 15;
select group_concat(year(now()),"-",month(now()),"-",15)
I got a table with two columns, timestamp (like '1405184196') and value.
I've saved some measured values.
$day= time()-84600;
$result = mysql_query('SELECT timestamp, value FROM table WHERE timestamp >= "'.$day.'" ORDER BY timestamp ASC');
This is how I get all values for the last 24h.
But is it possible to get average day values for the last month with a SQL statement or do I have to select all values of the last month and calculate the average of each day via PHP?
Several issues with Anish's answer:
1) This won't work if date+time is being stored in the timestamp field.
2) It assumes the OP means last month i.e June, May etc and not the last say 30 days.
This solves those issues:
SELECT DATE(`timestamp`) as `timestamp`, AVG(value)
FROM table
WHERE `timestamp` >= CURDATE() - INTERVAL 1 MONTH
GROUP BY DATE(`timestamp)
EDIT
Since the timestamp is a unix timestamp and the OP would like a calendar month:
SELECT DATE(FROM_UNIX(`timestamp`)) as `timestamp`, AVG(value)
FROM table
WHERE MONTH(FROM_UNIX(`timestamp`)) = MONTH(NOW() - 1)
GROUP BY DATE(FROM_UNIX(`timestamp))
You can do this:-
SELECT timestamp, AVG(value)
FROM table
GROUP BY timestamp
HAVING MONTH(timestamp) = MONTH(NOW()) - 1;
This query calculates average for last month.
DEMO
Say I've got a simple mysql table with columns id, title, date. Each day can have several rows, but not every day has a row. For example there might be 5 rows with June 15th as the date, but zero rows with June 14th as the date. How can I get all results from the past 7 days, excluding June 14th because it has no rows. So I'm not just subtracting 7 days from the current date. I want to get only the past 7 days which have any rows at all.
Then I want to return each day as a single result, like a group by date, but by the year/month/day part of the timestamp, so that what I get back is only 7 results, and each result is like an array of individual rows.
I hope that makes sense. Any ideas?
Edit:
I realized I can do it something like this:
WHERE Date BETWEEN DATE_SUB( NOW(), INTERVAL DATEDIFF( NOW(), (SELECT Date FROM test GROUP BY Date LIMIT 7,1 ) ) DAY ) and NOW()
But this gives an SQL syntax error. What I'm trying to do is a subquery and group by date to get one result for each day, and return one result starting at offset 7, then do a DATEDIFF on that to get the number of days that DATE_SUB should put in the INTERVAL x DAYS
You won't be able to get the same day results back as an array, but you can group it by date, with the titles comma separated:
SELECT GROUP_CONCAT(title) AS titles, date
FROM test
WHERE date > DATE_SUB(CURDATE(), INTERVAL 7 DAY)
GROUP BY date;
Then in PHP, do something like this:
foreach ($results as $row)
{
echo $row['date'];
foreach ($row['titles'] as $title)
{
echo $title;
}
}
Figured it out: It works!
WHERE Date BETWEEN DATE_SUB(NOW(), INTERVAL (DATEDIFF( NOW(), (SELECT Date FROM test GROUP BY Date ORDER BY Date DESC LIMIT 8,1 ) ) ) DAY) and NOW()
I was missing a parentheses, and I had to add ORDER BY and DESC to the subquery.
I have the following relation in my schema:
Entries:
entryId(PK) auto_inc
date date
In order to count the total entries in the relation I use a query in my php like this:
$sql = mysql_query("SELECT COUNT(*) as Frequency FROM Entries WHERE date = '$date'");
My question is how can I count the number of entries for the CURRENT month..
You want a between query based on your date column.
WHERE date BETWEEN startdate AND enddate.
Between is equivalent to date >= startdate AND date <= enddate. It would of course be also possible to just use >= AND < explicitly which would simplify it a bit because you don't need to find the last day of the month, but just the first day of the following month using only DATE_ADD(..., INTERVAL 1 MONTH).
However startdate and enddate in this case would be derived from CURDATE().
You can use CURDATE(), MONTH(), DATE_ADD and STR_TO_DATE to derive the dates you need (1st day of current month, last day of current month). This article solves a similar problem and all the techniques needed are shown in examples that you should be able to adapt:
http://www.gizmola.com/blog/archives/107-Calculate-a-persons-age-in-a-MySQL-query.html
The first day of the current month is obvious YEAR-MONTH(CURDATE())-01. The last day you can calculate by using DATE_ADD to add 1 Month to the first day of the current month, then DATE_ADD -1 Days.
update-
Ok, I went and formulated the full query. Don't think str_to_date is really needed to get the index efficiency but didn't actually check.
SELECT count(*)
FROM entries
WHERE `date` BETWEEN
CONCAT(YEAR(CURDATE()), '-', MONTH(CURDATE()), '-', '01')
AND
DATE_ADD(DATE_ADD(CONCAT(YEAR(CURDATE()), '-', MONTH(CURDATE()), '-', '01'), INTERVAL 1 MONTH), INTERVAL -1 DAY);
Try this
SELECT COUNT(1) AS `Frequency`
FROM `Entries`
WHERE EXTRACT(YEAR_MONTH FROM `date`) = EXTRACT(YEAR_MONTH FROM CURDATE())
See EXTRACT() and CURDATE()
Edit: Changed NOW() to CURDATE() as it is more appropriate here
Try
$sql = mysql_query("SELECT COUNT(*) as Frequency FROM Entries WHERE MONTH(date) = MONTH(NOW()) );