Count rows per date in a date range - mysql

I have been searching Google and SO for the last 25 min searching for how to do the following in MySQL.
I currently have the following query (Sent by PHP):
SELECT
COUNT(*),
`$db`.`crop`.`id` AS `crop`,
`$db`.`crop`.`harvest_date` AS `harvest_date`
FROM
`$db`.`crop`
WHERE
`$db`.`crop`.`harvest_date` BETWEEN $startDate AND $endDate
GROUP BY `$db`.`crop`.`harvest_date`
$startDate = 2012-01-01
$endDate = 2013-07-01
I am trying to find all the rows that have a harvest_date between start and end dates, and then count the number of rows that fall on the same date. However, I seem to be getting no results. The query doesn't fail, it just doesn't return anything. Can anyone point me in the right direction/tell me where I got it wrong?
EDIT: Found the problem. As Michael pointed out below, the dates were not getting passed as dates, but as numbers. I solved this by adding ' before and after startDate and endDate in the query.

MySQL expects date literals to be single-quoted strings like '2012-01-01' and '2013-07-01'.
Since you have not quoted your date literals which are PHP variables, PHP is actually interpreting them as arithmetic on integer values before it passes them into the query.
// You see this:
$startDate = 2012-01-01
$endDate = 2013-07-01
// PHP does this:
// 2012 - 1 - 1 = 2010
$startDate = 2010
// 2013 - 7 - 1 = 2005
$endDate = 2005
Your query ultimately uses this:
WHERE
`$db`.`crop`.`harvest_date` BETWEEN 2010 AND 2005
And MySQL will cast both of those integers to a DATE, which will return NULL.
mysql> SELECT CAST(2010 AS DATE);
+--------------------+
| CAST(2010 AS DATE) |
+--------------------+
| NULL |
+--------------------+
So the simple fix is:
$startDate = '2012-01-01';
$endDate = '2013-07-01';
And if you eventually convert this to a parameterized query, the correct quoting of placeholders would be handled for you.

To get the count between the given date range. Modify the query as
SELECT
COUNT(`$db`.`crop`.`id`),
FROM
`$db`.`crop`
WHERE
`$db`.`crop`.`harvest_date` BETWEEN $startDate AND $endDate
Grouping the result with "harvest_date" will determine the count for that particular date and group them.
example :
if the table is like
8-21-2013
8-21-2013
8-20-2013
then grouping will give
2
1
without grouping
3

I know this is an old post , but this worked for me
SELECT count(*),date(LSTUPDTIM),SUM(TOTAL) FROM order_table where LSTUPDTIM between '2018-01-20' and '2019-01-29' group by date(LSTUPDTIM) ;
,
my LSTUPDTIM is a TimeStamp which is why i had to use date()
which gave me an output like this
5 2019-01-25 500
2 2019-01-28 200
5 2019-01-29 500

Related

Selecting all rows before a given time in SQL

I have a fairly simple SQL table (using MYSQL Workbench 8.0) where the rows of the table contain dates and values like so:
date | value
--------------------|----------
2018-09-06 18:00:00 | 73
Values in the date column range from %18:00:00 to %17:30:00.
All I would like to do is return results from a query where I exclude all rows where the time in the date column is before 17:00:00.
The query I am currently using to no avail is:
SELECT * FROM table_name where td_time <> '%17%'
For reference, the values in column 'date' are formatted as type datetime.
I believe I'm missing something fairly simple, but this is my 2nd day using SQL and I cannot figure out if I am missing a small nuance to the syntax.
There are many function in MySQL to process time and date value, you can do like this:
select * from table where hour(date) < 17 and hour(date) > 17
Or
select * from table where time(date) < '17:00:00' and time(date) > '18:00:00'

mysql query to fetch the quarter month from table

Table name: activity
Field name: ProcessYM
I have mysql data like below.
ProcessYM
==========
201312
201311
201310
201309
201308
201307
201306
201305
201304
201303
201302
201301
201212
201211
201210
201209
201208
201207
201206
I want to fetch the result like below. I mean, the mysql query to fetch the every quarter of the year like 201312, 201309, 201306, 201303, 201212, 201209.. and so on.
Actual Output I expect
=======================
ProcessYM
201312
201309
201306
201303
201212
201209
201206
I have tried the below query, but it does not produce the expected result.
SELECT distinct `ActProcessYM` from `activity` where `ActProcessYM`%3=0 order by ActProcessYM desc
Output of above query
=====================
201312
201309
201306
201303
201210
201207
It is much appreciated for your smart reply.
You need to modulo of the month part only. Your query is implicitly casting your ProcessYM as an INT.
For example:
SELECT DISTINCT ProcessYM
FROM activity
WHERE RIGHT(ProcessYM,2)%3=0
ORDER BY ProcessYM DESC
fiddle
you should retrieve the last two digits from field value and do the logic as you are doing.
SELECT distinct `ActProcessYM` from `activity` where substring(ActProcessYM,5,2)%3=0 order by ActProcessYM desc
Here's a not-so-quick-and-dirty way of handing this date processing. I believe you're looking for a MySQL formula like this:
yyyymm = TRUNC_QUARTER(yyyymm)
That is, you are looking for a function that converts any yyyymm month notation into a notation that shows the month that ends the quarter in question.
Let's start with an expression that converts any particular DATETIME expression to the DATE of the beginning of the quarter.
DATE(CONCAT(YEAR(value),'-', 1 + 3*(QUARTER(value)-1),'-01'))
This takes a timestamp (e.g. '2011-04-20 11:15:01') and turns it into the date of the starting of the quarter. (e.g. '2011-04-01')
Having things in this date form is helpful because you can use them for date arithmetic. For example, you can get the last day of that quarter like this.
DATE(CONCAT(YEAR(value),'-', 1 + 3*(QUARTER(value)-1),'-01'))
+ INTERVAL 1 QUARTER - INTERVAL 1 DAY
Here's a writeup on all this: http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/
I've found it helpful to try to stick to the date datatype when processing time series data.
You need to separate out the month value before doing the modulo 3 (% 3). Doing a modulo 100 first will do it:
(ProcessYM % 100) % 3) = 0
or
mod(mod(ProcessYM,100),3) = 0
Try this,
SELECT distinct `ProcessYM` from `activity` where SUBSTRING(`ProcessYM`,5,2)%3=0 order by ProcessYM desc

Count all database entries separated by days

I have a table with the following format:
offer_id consumer_id date
1 1 1282454200
1 1 1282453200
2 2 1282453240
1 3 1282455200
2 1 1282453210
"date" is in unix format.
I need to count all of the daily entries, so if I have 10 entries from yesterday and 8 entries from today, I should get:
2013-06-23 10
2013-06-24 8
This is part of my work on trying to optimize code, so far I have been doing this via PHP code, but you can imagine what happens with a growing database :). This is my php (codeigniter) attempt that I'm trying (unsuccessfully) to translate into mysql:
foreach ($offers as $item) {
$date = $item->date;
$day_date = date("Y-m-d", $date);
$day_start = strtotime(date("Y-m-d 00:00:00", $date));
$day_end = strtotime(date("Y-m-d 23:59:59", $date));
if (!in_array($day_date, $day_array)) {
$day_array[] = $day_date;
$this->db->where("date >=", $day_start);
$this->db->where("date <=", $day_end);
$this->db->from("offers_consumers_history");
$total_points = $this->db->count_all_results();
$db_date = array($day_date, $total_points);
$data[] = $db_date;
}
}
I basically grabbed all of the entries in a previous query and went through every date, if the date isn't in my final array, I had to it by counting all results from 00:00:00 to 23:59:59.
Looking for help in building equivalent SQL code.
You could use this SQL query:
SELECT DATE(FROM_UNIXTIME(date)), COUNT(*)
FROM offers_consumers_history
GROUP BY DATE(FROM_UNIXTIME(date))
Please see fiddle here.
Try like
SELECT count(*) as cnt , date FROM `my_table` GROUP BY date
Then you can change them as your required format.It is simple and same that to change the dates into FROM_UNIXTIME and then counting
If I have right understood your question, group by is what you need

I am trying to select all the values from a table using date in SQL Server 2008

I am trying to select all the values from a table using date in SQL Server 2008. The problem is the date column in the DB is in Datetime format. But the thing is I have to select all the values from the database by using date
I used the following query
select *
from Table
where subdate = '2012-12-12'.
It won't return any value....
My table is like this
Subdate val1 val2 val3 name
-------------- ----- ----- ---- -----
2012-12-12 12:32:12.000 2 1 2 ben
2012-12-27 15:17:32.533 2 1 2 yen
2012-12-27 15:20:06.660 2 1 2 sun
Thanks in advance.........
select * from Tble where subdate>='20121212' and subdate <'20121213'
would be my usual recommended approach(*). If it's a parameter, it would be:
select * from Tble where subdate>=#Parm and subdate <DATEADD(day,1,#Parm)
'2012-12-12' and '2012/12/12' can be subject to weird conversion issues, depending on your language/date settings on the server. '20121212' will always be converted as YYYYMMDD.
(*) I don't use BETWEEN for such comparisons, because you either include two midnights , or you have to calculate the last moment before midnight of the following day. Which would be at 23:59:59.997 if you're using datetime, but suddenly changes to being something else for datetime2.
SELECT *
FROM Table
WHERE CAST(subdate AS DATE)='2012-12-12'
Raj
The date in the table also contain Time so you have to convert that date to the format suitable for the date you enter.
You have to use: Sql Server Date Formats
select * from Tble where CONVERT(VARCHAR(10), subdate, 111) = '2012/12/12'
Demo SQLFiddle

MySQL MONTH returns wrong results

The following query didn't return correct results, because it returns results from "September" month but i need to get results from given month "August".
Is there something wrong in my query?
SELECT *
FROM table
WHERE YEAR(FROM_UNIXTIME(UNIX_date)) = '2012' AND
MONTH(FROM_UNIXTIME(UNIX_date)) = '08'
order by UNIX_date DESC
EDIT:
results that returned were like that:
post_id user_id UNIX_date
95319 12 1346475459
97370 5 1346474849
83527 25 1346474631
83526 51 1346473357
85929 12 1346471009
26677 29 1346462100
26839 12 1346432911
85927 12 1346411636
The month should not have a leading 0. So try 8 instead of 08.
You could also post a line of what is being returned so we can see how UNIX_date looks like.
reference: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_month
As written in the documentation http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_month, the DAY, MONTH and YEAR functions returns integer, thus values 1-12 (or zero) for the MONTH.