How to query date per fiscal year (time in epoch) - mysql

I have an inventory database, on the database I'm storing multiple Items with the date that the item was created.
The date is in epoch time.
What I need to do is to create a report per fiscal year - in this case from sept 1, 2020 to Aug 30, 2021, it is possible to do this query if I have the time on epoch or it easier if I store the date on a different format.
id | name | status | time
1 | pens | active | 1636395754

It's possible using FROM_UNIXTIME function. Example query:
SELECT *,
FROM_UNIXTIME(time)
FROM mytable
WHERE FROM_UNIXTIME(time) >= '2020-09-01'
AND FROM_UNIXTIME(time) <= '2021-08-31';
If you want to add a new time column in UTC format based on the existing time column, you can do like this (provided that you have the access privilege):
ALTER TABLE mytable ADD utctime DATETIME;
Then UPDATE the new column:
UPDATE mytable SET utctime=FROM_UNIXTIME(time);
Demo fiddle

Related

Write SQL query to output the Maximum number and Minimum number of movies produces by diffrent actors and actresses between year 1991 and 2001

I need to write SQL query to output the Maximum number and Minimum number of movies produces by diffrent actors and actresses between year 1991 and 2001
query written . When I tried this, I got error enter image description here
The expected result is to output the maximum numer each actor or atress produces within that year range
The result should look like this
When I tried this, I got error what i tried
The expected result is to output the maximum number each actor and atress produces within that year range
The result should look like this
Data type Description
DATE A date. Format: YYYY-MM-DD.
DATETIME(fsp) A date and time combination. Format: YYYY-MM-DD hh:mm:ss.. Adding DEFAULT and ON UPDATE in the column definition to get automatic initialization and updating to the current date and time
TIMESTAMP(fsp) A hh:mm:ss. The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC. Automatic initialization and updating to the current date and time can be specified using DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP in the column definition
TIME(fsp) A time. Format: hh:mm:ss. The supported range is from '-838:59:59' to '838:59:59'
YEAR A year in four-digit format. Values four-digit format: 1901 to 2155, and 0000.
MySQL 8.0 does not support year in two-digit format.
Oracle dates contain both date and time so if you're looking to test years only you need to extract that part of the date
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';
CREATE TABLE t1 (datestamp) AS
SELECT DATE '2022-10-17' FROM DUAL UNION ALL
SELECT DATE '2022-12-03' FROM DUAL UNION ALL
SELECT DATE '2021-04-03' FROM DUAL UNION ALL
SELECT DATE '2021-05-10' FROM DUAL;
select * from t1
where extract(YEAR from datestamp) = 2021
DATESTAMP
03-APR-2021 00:00:00
10-MAY-2021 00:00:00
select * from t1
where extract(MONTH from datestamp) = 04
DATESTAMP
03-APR-2021 00:00:00
select * from t1
where extract(DAY from datestamp) = 10
DATESTAMP
10-MAY-2021 00:00:00
If you don't want to use the extract method you can do the following. Note since dates contain time you need the +1 to include any dates on 2021-04-30 that fall between the times 00:00:00 and 23:59:59
select * from t1
WHERE datestamp >= DATE'2021-04-01' AND
datestamp <DATE'2021-04-30' +1
DATESTAMP
03-APR-2021 00:00:00
Whenever you have a question, please post a little sample data (CREATE TABLE and INSERT statements for all tables involved, relevant columns only) so the people who want to help you can recreate the problem and test their ideas. Also post the exact results you want from that data, and explain why you want those results from that data. Lastly, don't post any images as they can't be cut and pasted.

get all row entries based on month/year in MySQL

I have a database with the following structure and I am trying to get all rows from this table based on passing both the month and year using a where on the timestamp column (this will be a unix standard timestamp)
e.g month - 3, year - 2018 // get all rows for March 2018 only.
// db structure
id, timestamp, post_title
If you want rows for a given month using a unix timestamp, I would recommend:
where timestamp >= unix_timestamp('2018-03-01') and
timestamp < unix_timestamp('2018-04-01')
If you are passing in a variable, I would recommend passing in the first day of the month and doing:
where timestamp >= unix_timestamp(?) and
timestamp < unix_timestamp(? + interval 1 month)
Use convert function
SELECT * FROM dbo.YourTable WHERE CONVERT(VARCHAR(5),DATEPART(mm,timestamp))+'-'+CONVERT(VARCHAR(5),DATEPART(yy,timestamp)) ='3-2018'
I guess this can help you.
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

MySQL; SELECT all records from yesterday (midnight to midnight) using a location's timezone [duplicate]

This question already has answers here:
Can MySQL convert a stored UTC time to local timezone?
(6 answers)
Closed 6 years ago.
How do I SELECT all records from yesterday, from Midnight to Midnight, for a specific location's timezone (timestamps all in UTC and locations have named timezones - e.g. America/Vancouver)?
Please note that I'm not asking how to convert a date and time to another timezone. What I'm asking is how [best] to localize a date range comparison.
Assuming the timezone for your MySQL database session is UTC (i.e. time_zone='+00:00')...
And assuming that you want to use the same timezone for all of the rows (i.e. not different timezones based on contents of the row ...
Take the value for "midnight" in the user's specified timezone, and convert that to UTC. e.g. 2016-04-16 00:00 CST6CDT (i.e. America/Chicago) converts to 2016-04-16 05:00 UTC.
Assuming that your table column is named utc_timestamp_col, and is datatype TIMESTAMP, your query would look look something like this:
SELECT ...
FROM mytable t
WHERE t.utc_timestamp_col >= '2016-04-16 05:00' + INTERVAL -1 DAY
AND t.utc_timestamp_col < '2016-04-16 05:00' + INTERVAL 0 DAY
If you have populated the MySQL timezone tables, you can make use of the MySQL support for named timezones. http://dev.mysql.com/doc/refman/5.7/en/time-zone-support.html
You can build an expression that gets you previous "midnight" in a named timezone.
Below is a demonstration query:
verify session time_zone is UTC
return current date and time in UTC
convert to local time zone CST6CDT
truncate to midnight
convert back to UTC
e.g.
SELECT ##session.time_zone AS `time_zone`
, NOW() AS `now_utc`
, CONVERT_TZ(NOW(),'UTC','CST6CDT') AS `now_CST6CDT`
, DATE(CONVERT_TZ(NOW(),'UTC','CST6CDT')) AS `midnight_CST6CDT`
, CONVERT_TZ(DATE(CONVERT_TZ(NOW(),'UTC','CST6CDT')),'CST6CDT','UTC')
AS midnight_CST6CDT_utc
Returns:
time_zone now_utc now_CST6CDT midnight_CST6CDT midnight_CST6CDT_utc
--------- ------------------- ------------------- ---------------- --------------------
UTC 2016-04-17 01:53:31 2016-04-16 20:53:31 2016-04-16 2016-04-16 05:00:00
Demonstrating the same thing, using time zone named 'America/Chicago'
SELECT ##session.time_zone AS `time_zone`
, NOW() AS now_utc
, CONVERT_TZ(NOW(),'UTC','America/Chicago') AS `now_America/Chicago`
, DATE(CONVERT_TZ(NOW(),'UTC','America/Chicago')) AS `midnight_America/Chicago`
, CONVERT_TZ(DATE(CONVERT_TZ(NOW(),'UTC','America/Chicago')),'America/Chicago','UTC')
AS `midnight_America/Chicago_utc`
returns the same result:
time_zone now_utc now_America/Chicago midnight_America/Chicago midnight_America/Chicago_utc
--------- ------------------- ------------------- ------------------------ ----------------------------
UTC 2016-04-17 01:57:19 2016-04-16 20:57:19 2016-04-16 2016-04-16 05:00:00
FOLLOWUP
If I needed to do that kind of timezone conversion in the query, I would use an inline view to return the value from that fairly complicated expression, to make the outer statement simpler. For example, the inline view aliased as "d" returns the value as column named "dt", which can be referenced in the outer query.
Since that inline view returns exactly one row, we can use a JOIN to mytable without duplicating any rows. We can move the predicates from the WHERE clause to an ON clause. e.g.
SELECT ...
FROM ( SELECT CONVERT_TZ(DATE(CONVERT_TZ(NOW(),'UTC','CST6CDT')),'CST6CDT','UTC') AS dt
) d
JOIN mytable t
ON t.utc_timestamp_col >= d.dt + INTERVAL -1 DAY
AND t.utc_timestamp_col < d.dt + INTERVAL 0 DAY

Count number of Distinct days in query

We have a table that has a StartDate field which holds a type of datetime. There are thousands of records and I am looking for a way to find the number of days within a given result returned from this table. For instance, if my table had this data:
ID | StartDate
--------------
1 01/01/2013 09:34:54
2 01/01/2013 11:23:21
3 04/11/2013 14:43:23
4 04/11/2013 17:13:03
5 04/25/2013 18:02:59
6 07/21/2013 02:56:12
7 10/01/2013 19:43:10
Then the query should return 5 as the 2 dates on 01/01/2013 count as 1 and the same for 04/11/2013.
The only SQL I've been able to come up with is:
SELECT COUNT(DISTINCT(DATEPART(DAY, StartDate)))
FROM Stats
WHERE StartDate BETWEEN '01/01/2013' AND '12/31/2013' --This is just for filtering
But this returns 4 because it doesn't take the month into account.
Any help is appreciated.
You can CAST as date
SELECT COUNT(DISTINCT CAST(StartDate AS DATE))
FROM Stats
WHERE StartDate >= '20130101' AND StartDate < '20140101'
Also use an unambiguous date format such as yyyymmdd and >= < not BETWEEN.
Your current query would include the 31st December if there was a row with exactly the value 20131231 00:00:00 but not any with different times on that date. I doubt that is intentional.

group by month of unix timestamp field

I'm trying to get my code to output in the following format:
january 2012 - 34
february 2012 - 23
where 34 and 23 would be a count of the total rows that fall within that month that have the id_dealership of 7. I need this to output all data for every month that an assignment was ever made.
The assignments table structure is as follows:
id_dealer (int)
date_assigned (int)
I've tried this but it does not work at all:
SELECT MONTH(date_assigned), YEAR(date_assigned), COUNT(*)
FROM assignments
GROUP BY MONTH(date_assigned), YEAR(date_assigned)
SELECT
MONTH(FROM_UNIXTIME(date_assigned)),
YEAR(FROM_UNIXTIME(date_assigned)),
COUNT(*)
FROM assignments
GROUP BY
MONTH(FROM_UNIXTIME(date_assigned)),
YEAR(FROM_UNIXTIME(date_assigned))
Your date_assigned column should be of type DATE. AFAIK MONTH works on date columns
and if you want the month name from a DATE column use : MONTHNAME(date_assigned)
try this query
SELECT
MONTH(FROM_UNIXTIME(date_assigned)),
YEAR(FROM_UNIXTIME(date_assigned)),
COUNT(*)
FROM assignments
GROUP BY 1,2
For people who would like to output a DATETIME rather than a month/year combo, here's another way to solve the problem. The benefit of using DATETIME is that it can easily be plugged into data visualization libraries and tools.
SELECT
LAST_DAY(FROM_UNIXTIME(date_assigned)),
COUNT(*)
FROM assignments
GROUP BY 1
ORDER BY 1 DESC
The LAST_DAY() function returns the last day of the month for a given DATE or DATETIME value. If you'd rather grab the first day, you could select this instead: ADDDATE(LAST_DAY(SUBDATE(FROM_UNIXTIME(date_assigned), INTERVAL 1 MONTH)), 1). It adds a day to the last date then subtracts a month.
The 1 values are column position integers -- shorthand so we don't have to type LAST_DAY(FROM_UNIXTIME(date_assigned)) any more than we need to (they start at 1, not 0).
Example output:
|-------------------------------------------|------------------|
| LAST_DAY(FROM_UNIXTIME(date_assigned)) | COUNT(*) |
|-------------------------------------------|------------------|
| September 30, 2020, 12:00 AM | 34 |
|-------------------------------------------|------------------|
| August 31, 2020, 12:00 AM | 23 |
|-------------------------------------------|------------------|