MySQL: Selecting In Between DateTime records - mysql

I want to get the count of records between two date-time entries.
I have a column in my table named created_date with the datetime data type.
I want to select rows which were created between 2017-01-10 and 2017-01-30
I have written the following query but it doesn't seem to be inclusive
SELECT* FROM table WHERE created_date BETWEEN '2017-01-10' AND '2017-01-30'

The issue you are having has to do with that the date literal 2017-01-31 represents that date at midnight. To get around this, phrase your query as follows:
SELECT * FROM table WHERE created_date >= '2017-01-10' AND created_date < '2017-01-31';
This says to take any date on or after the very start of 2017-01-10 and before the start of 2017-01-31. This implies including the entire day 2017-01-30.

For get count of records between two date you can try below query
SELECT COUNT(*)
FROM tableName
WHERE date(created_date) >= '2017-01-10' AND date(created_date) <= '2017-01-30'

Try This One
SELECT COUNT(1)
FROM tableName
WHERE Cast(created_date as date) Between Cast('2017-01-10' as date) AND Cast('2017-01-30' as date)

Related

How to select range of data between latest DateTime minus 30 minutes

I'm trying to figure out how to select the latest DateTime value in a table and all previous data that came with it in a 30 minute window using MySQL.
eg table:
DateAndTime
---------
09:00:00
08:59:50
08:59:40
08:59:30
08:59:20
08:59:10
08:59:00
08:58:50
08:59:40
...
...
08:30:00
I am selecting max time as such:
SELECT MAX(`DateAndTime`) AS "DateAndTime"
FROM TableA;
I have been trying the INTERVAL() function, but I can't seem to get that to return any other rows other than the max time.
What I tried:
SELECT MAX(`DateAndTime`) AS "DateAndTime"
FROM TableA;
AND `DateAndTime` - INTERVAL 30 MINUTE;
We can use your query as subquery in the WHERE clause:
SELECT DateAndTime
FROM tableA
WHERE DateAndTime >=
(SELECT MAX(DateAndTime) - INTERVAL 30 MINUTE
FROM tableA);
If we want to select further columns, we will just add them in the main query.
If we want to make sure the result will be sorted by date, we will add an ORDER BY clause:
SELECT DateAndTime
FROM tableA
WHERE DateAndTime >=
(SELECT MAX(DateAndTime) - INTERVAL 30 MINUTE
FROM tableA)
ORDER BY DateAndTime;
It looks like you'll need a subquery because you need an aggregate function to find the latest timestamp, then to use that value to return the rows you need. Try this:
SELECT DateAndTime
FROM TableA a
WHERE DATE_ADD(a.DateAndTime, INTERVAL 30 MINUTE) >=
(SELECT MAX(DateAndTime) FROM TableA)

How to select either one row or the other

I have a table with columns VAT, start and end date.
I have two rows. The standard entry has 0000-00-00 as the start and end date and the other row has the start_date 2020-06-01 and the end_date 2020-12-31
I want VAT of the second row to be selected if today's date is between the start and end date, otherwise the standard VAT with 0000-00-00 should be selected
This is my table:
I tried
SELECT *
FROM taxes
WHERE (CASE WHEN start_date < "2020-06-06"
AND end_date > "2020-06-06" THEN 1
ELSE 0
END) = 1
But i don't know how to formulate the else case or whether it can work at all like this
You can use order by and limit for this:
select t.*
from taxes t
where start_date = '0000-00-00' or
'2020-06-06' between start_date and end_date
order by start_date desc
limit 1;
The idea is that the first condition gets the "default" value. The second condition gets the matching condition. These two rows are then sorted, so the matching condition will be first -- if there is one.
There might be ways o doing it with your suggested "0000-00-00' dates for start and end points, but in my view you run a much cleaner ship if you address the time spans individually, i. e. spell out the date ranges for before and after the "exception period", like:
INSERT INTO vat (startdt,enddt,fullrate,reducedrate)
VALUES ('2000-01-01','2020-06-30',.19,.07), -- before
('2020-07-01','2020-12-31',.16,.05), -- exception period
('2021-01-01','2500-12-31',.19,.07); -- after
select * from vat where now() between startdt and enddt;
This way you document in a very clear way which rates were applicable when. And the query itself becomes trivial, see above and check out my demo here: https://rextester.com/YLYUU53617
SELECT *
FROM taxes
WHERE tax_id=IF(start_date < "2020-06-06" AND end_date > "2020-06-06", 1, 0)
you can find the records for current date, then combine this set with the source table filtered by '0000-00-00' excluding country codes from this set
with
current_taxes as (
select *
from taxes
where current_date between start_date and end_date
)
select *
from current_taxes
union all
select *
from taxes
left join current_taxes
using (country_code)
where taxes.start_date='0000-00-00'
and current_taxes.country_code is null
;

I need the way to aggregate based on column value using MySQL

I am learning Charts in Laravel, i need to draw Line graph for daily Student Attendance for those students come late or on time. I tried to write MYSQL query but it doesn't work
I tried subquery on same table to get data for daily students and i also need 7 dates only not full date, like date is stored in db as 09/08/2019 but i need it as 08 as date.
SELECT Date, COUNT(*) AS TimeStudent
FROM attendance WHERE `Attendance`='OnTime' AND (SELECT COUNT(*) AS
LateStudent FROM attendance
WHERE `Attendance`='Late'
GROUP BY `Date`
ORDER BY LateStudent DESC)
GROUP BY `Date`
ORDER BY TimeStudent DESC
but i got
[Err] 1241 - Operand should contain 1 column(s)
, because i can't use to fetch Date again in subquery while use it after where clause. Any one help me plz.
Here is a way to aggregate based on column value.
This query will give you count of on time and late student for a particular date.
SELECT
`Date`,
DATE_FORMAT(`Date`, '%d') AS Month_Date, -- You can modify it as per your requirement
SUM(IF(`Attendance` = 'OnTime', 1, 0)) AS OnTime_Count,
SUM(IF(`Attendance` = 'Late', 1, 0)) AS Late_Count
FROM attendance
WHERE `Date` >= CURRENT_DATE - INTERVAL 7 DAY
GROUP BY `Date`;

How can i include previous row in a selected range if condition is not satisfied

I am trying to find out a maximum number from a given date ranges.
for example, my table contains
date number
---------- --------
01-01-2019 1
05-01-2019 3
07-01-2019 2
10-01-2019 1
11-01-2019 2
and I want to find the max number in date from 06-01-2019 to 11-01-2019
When I use the query,
select max(count) from TABLE where date between startDate and endDate;
the output is 2.
But what I wanted is if the startDate is not in the table, to include the previous row. For example in the previous case, I want to include the row 05-01-2019 and thus the output should be 3.
Is there any query for this process or do I need to write an algorithm?
Assume the dates in table are sorted and I use a MySQL database.
You can do this by using subquery
SELECT MAX(number)
FROM TABLE
WHERE date >= (
SELECT date
FROM TABLE
WHERE date <= startDate
ORDER BY date DESC
LIMIT 1
)
AND date <= endDate
Subquery will return largest nearest date to startDate.
This date can then be used as a minimum value for your outer query.
In MySQL 8+, you can use lead():
select max(number)
from (select t.*, lead(date) over (order by date) as next_date
from t
) t
where next_date > $start_date and
date <= $end_date;

Select all distinct values where datestamp is in the last 24 hours and order by total rows ASC

I have a query I am trying to formulate, but it keeps giving me unexpected results.
What I need to do is:
select all distinct values from my table where the unix timestamp is >= the last 24 hours, then order these results by which one has the highest amount of entries.
I have managed the time part:
SELECT DISTINCT(column_name) as myValue from table_name WHERE time_column >= unix_timestamp(CURRENT_TIMESTAMP, INTERVAL 1 DAY)
This works as expected. Then I was just going to use PHP to sort through the results etc etc, however I wish to use the power of SQL on this one.
Any ideas how I can extend the above query to encapsulate counting the amount of distinct column_name values? Also to then sort this in order dependent on how many values are in each one?
So essentially I want to get my results like so :
a unique ID | highest amount
a unique ID | second highest amount
a unique ID | lowest amount
I think you want to use group by for this query:
SELECT column_name as myValue, count(*) as cnt
from table_name
WHERE time_column >= unix_timestamp(CURRENT_TIMESTAMP, INTERVAL 1 DAY)
GROUP BY column_name
ORDER BY cnt;
I managed to figure it out, and in my case it works perfectly:
SELECT column_name, COUNT(*) as myValue
FROM table_name
WHERE time_column >= unix_timestamp(CURRENT_TIMESTAMP - INTERVAL 1 DAY)
GROUP BY column_name
ORDER BY myValue DESC
This gave me the 3 values which I expected. Which were the 3 values in the last 24 hours, and they were ordered by the amount of occurrences of this were in the database table - I tested this by manually creating another occurrence of these and checking at each stage. Worked a treat