get Date range when there are no date exists in table - php

This is my query it's working fine.
But i want to get the blank record with the missing date, when there is no record exist for that date range, while fetching data from table.
SELECT * from tbl_social where `dCreatedDate` BETWEEN
DATE_ADD('2015-07-06', INTERVAL 3 DAY) and DATE_SUB('2015-07-06', INTERVAL 3 DAY);
if there is no record for date '2015-07-08' i need that date row also in listing.
Thanking you.

You can make some changes to the query and bring all that data which is not in this particular range
and also has no date . to do so try something like this
SELECT * FROM SELECT * from tbl_social
WHERE (
`dCreatedDate` NOT BETWEEN DATE_SUB('2015-07-06', INTERVAL 3 DAY)
AND DATE_ADD('2015-07-06', INTERVAL 3 DAY)
) OR (`dCreatedDate` IS NULL )
with NOT BETWEEN it will seek those records which dont fit the criteria and with NULL it will see for those records whose dCreatedDate is blank and fetch all the data matching both criteria

Related

Show all dates even those with zero data in it in mySQL?

My following query shows the date and the count of the emails found on each day (last 2 days)
My problem is that if no emails are found today, the today date will not be displayed on the output. (if yesterday has emails, it will show only 1 row with yesterday date and email).
How can I edit my query to always show 2 rows, today and yesterday, date and number of emails even zero?
SELECT maildate,
COUNT(*) AS totalEmails
FROM emails
WHERE maildate >= Date_add(Curdate(), interval - 2 DAY)
AND company_id = 1
GROUP BY DATE(maildate)
ORDER BY maildate desc
There are many tricks to creating a list of dates (or numeric sequences similarly). The one I like to use with MySQL is using #sqlvariables. I will typically start with a baseline value such as your date -2 days. I will do a cross-join to any other table in the database that has at least as many records as you expect in your output... Say 30 days, or a whole year 366 days, or longer. The inner sql variable prep will keep increasing itself by whatever increment (you could even do date ranges such as begin/end of a week, month, etc). Now you have your table of all possible dates you are looking to fill.
Now, I do a secondary query by the value -- in this case your email date and apply the group by. Using the where clause in this query will make IT faster since it can utilize the date on its query result set before returning for the LEFT-JOIN to the date range result set.
Now, your simple left-join gets both parts of all dates to be included and those corresponding counts that do exist.
Note the table alias "AnyTableWithAtLeast3RecordInIt" in the "JustDates" query could in-fact be your "emails" table. Since we don't care about any criteria except a record exists, and we are applying a limit of 30 days in my example, it will be instantaneous.
select
JustDates.DateToInclude,
coalesce( SumCnts.TotalEmails, 0 ) TotalEmails
from
( select
#myDate := DATE_ADD( #myDate, INTERVAL 1 DAY ) as DateToInclude
from
( select #myDate := Date_add(Curdate(), interval - 2 DAY) ) as SQLVars,
AnyTableWithAtLeast3RecordInIt
limit 30 ) JustDates
left join
( select
maildate,
COUNT(*) AS totalEmails
FROM
emails
WHERE
maildate >= Date_add(Curdate(), interval - 2 DAY)
AND company_id = 1
GROUP BY
DATE(maildate) ) SumCnts
ON JustDates.DateToInclude = SumCnts.MailDate
Now, judging by your query, but unclarified request... Your emails table CAN HAVE FUTURE DATES? Is that correct? Such as a Dr. Office and appointments are for the future and you want to get emails out for a given range. This is what I was inferring and hence had my limit to only go out 30 days... If you need longer, just extend the LIMIT clause.
You need a table that contains all dates in the needed range. If its only about today and yesterday, you can easily create it as a subquery (derived table).
SELECT Curdate() as maildate
UNION ALL
SELECT Curdate() - INTERVAL 1 DAY
http://rextester.com/ALH50651
Now you can LEFT JOIN your table and count the rows:
SELECT sub.maildate,
COUNT(m.maildate) AS totalEmails
FROM (
SELECT Curdate() as maildate
UNION ALL
SELECT Curdate() - INTERVAL 1 DAY
) sub
LEFT JOIN emails m
ON DATE(m.maildate) = sub.maildate
AND m.company_id = 1
GROUP BY sub.maildate
ORDER BY sub.maildate desc

create mysql query for fetching data in 3 days slotwise

I want to create a query for fetch all the data from database. But condition is get from before current month and data will convert into 3 days slot wise with count.Like if i have 12 month data and in July 1 to 3 date data will insert into 50 rows and from 3 to 6 date data will insert into 5 rows.How i fetch this things.That is the mail problem. I have wondered but nothing found related my problem. Is this possible.
I assume you have a DATE or a DATETIME column, that marks the day of the insert, say the column created_at. Then you could get the desired result.
SELECT
COUNT(*)
FROM
your_table
WHERE
created_at BETWEEN '2014-07-01' AND '2014-07-31 23:59:59'
GROUP BY
(DAYOFMONTH(created_at) - 1) DIV 3
Explanation:
With the help of the DIV operator you get your 3-day-slots.
Note
If there's a slot without rows, it won't be in the result. To get these too, you could use a LEFT JOIN with the maximum 11 slots.
Demo
If you having timestamps as attribute type then might be this help you
SELECT count(*) as count
FROM table
AND
TIMESTAMPDIFF(DAY,date,2014-08-01)<=3";
The date is the attribute of your column, TIMESTAMPDIFF will find difference between given date if it's under 3 days from 2014-08-01 records will show up. This way by just sending one date into this position you can find 3 slots of date from your table.

Php mysql get the nearest-latest record if a record is not exist (datetime based)

Trying to get my head around, If I select a record such as WHERE item_id='$item_id' AND date(datetime)='2012-06-25' and if that record does not exist so I want to get the nearest-latest record after that date. How can I achieve that in a query?
All I can think of the only way right now is if num_of_rows is 0 then I add 3 days period ahead to that day and search again and get the DESC datetime LIMIT 1 (in case there are multiple rows). But who knows I can do it with just a query.
The record could have multiple rows in one day. So if a particular date has no record, how to get the next nearest available data given the same $item_id?
SELECT *
FROM table
WHERE field <= '2012-06-25'
ORDER BY field DESC
LIMIT 1
I think this is what you are looking for:
SELECT *
FROM my_table
WHERE datetime BETWEEN '2012-06-25 00:00:00' AND
DATE_ADD('2012-06-25 00:00:00', INTERVAL 3 DAY)
ORDER BY datetime ASC
LIMIT 1;
also create index on field datetime for faster performance.
This will bring back the item closest to the date that you enter into the query. It won't however look for before or after, just find the closest date to what you enter in.
select
min(abs(DATEDIFF(date(datetime),'2012-06-25'))) as minDiff
,yourID
from table1
group by yourID
order by 1 asc;

Group and manipulate based on multiple columns

I have a table that inserts a row when a certain function is used on the site and stamps the date.
code-/----date----/--type
-----/------------/------
--1--/--2012-2-1--/-used
--1--/--2012-2-3--/-saved
--1--/--2012-1-3--/-printed
--2--/--2012-2-1--/-used
--2--/--2012-2-2--/-printed
I have to report the number of times code 1 was (printed or saved or used) today, or yesterday, or last month (date range)
I am starting with this:
$stat_query = mysql_query("SELECT code, type, date FROM tracking WHERE code IN ('$htL','$htG','$htR') GROUP BY code, type, date");
I use the IN operand because each user has 3 codes to track with limitless date entries for each type.
I really am lost as to what to do here.
You'll need to construct the date ranges and modify the query. Below is an example of showing the count for code in the past day:
SELECT `code`, COUNT(`code`) as code_cnt
FROM tracking
WHERE
`code` IN ('$htL','$htG','$htR') AND
`date` BETWEEN DATE_SUB(now(), INTERVAL 1 HOUR) AND now()
GROUP BY `code`
Check out the DATE_SUB documentation for further help
GROUP BY code, type, date in this example makes it to return only one record. Because all code rows would be summerized in distinct output row, also type would be reduce more and more. Please check your GROUP BY fields.

Fetching each records in MySQL table within specific date range

can anyone suggest me way to display all records in MySQL table within a specific date range, and if no records available on the date, it will still display as NULL?
SELECT * FROM table_name WHERE date IS NULL OR date BETWEEN 'date1' AND 'date2';
If you wish to include date2 with the result, use this
SELECT * FROM table_name WHERE date IS NULL OR date BETWEEN 'date1' AND ADDDATE('date2', INTERVAL 1 DAY);

Categories