MySQL query - Date Range - mysql

Hi I'm using the MySQL query below along side Grafana, and data relating to my electricity usage. The data collected ranges from late 2021 to current date, however the result only ranges from December 21 to November 22.
SELECT
Time AS "time",
SUM(Rate/800) as kWh
FROM Log
GROUP BY MONTH(STR_TO_DATE(time, "%Y-%m-%d"))
Can someone kindly assist with amending the query to display all relevant months from 2021 to 2023 and so on please.

Please add your table structure and some sample data to your question.
Your current query is non-deterministic, and if you had ONLY_FULL_GROUP_BY enabled, would be failing with a 1055 error. You can read more about MySQL Handling of GROUP BY here.
You are grouping by MONTH(STR_TO_DATE(time, "%Y-%m-%d")) which will return 1 for 2021-01-02, 2022-01-03 and 2023-01-04. You need to group by both the year and month.
If you run this modified version of your query you should be able to see what is happening:
SELECT
MONTH(STR_TO_DATE(`Time`, '%Y-%m-%d')) AS `m`,
MIN(`Time`) AS `min_time`,
MAX(`Time`) AS `max_time`,
SUM(`Rate`/800) AS `kWh`
FROM `Log`
GROUP BY MONTH(STR_TO_DATE(`Time`, '%Y-%m-%d'));
Your use of STR_TO_DATE() appears unnecessary as you are using the standard date format %Y-%m-%d.
SELECT
DATE_FORMAT(`Time`, '%Y-%m-01 00:00:00') AS `time`,
SUM(`Rate`/800) AS `kWh`
FROM `Log`
GROUP BY `time`
With the date format '%Y-%m', 2021-01-02, 2022-01-03 and 2023-01-04 will be returned as 2021-01, 2022-01 and 2023-01 respectively, and grouped in the correct month.

Try this :
SELECT
Concat(YEAR(STR_TO_DATE(Time, "%Y-%m-%d")),'-', MONTH(STR_TO_DATE(Time, "%Y-%m-%d"))) as month,
SUM(Rate/800) as kWh
FROM Log
GROUP BY YEAR(STR_TO_DATE(Time, "%Y-%m-%d")), MONTH(STR_TO_DATE(Time, "%Y-%m-%d"))

You can use this query to get your desired output :
SELECT
DATE_FORMAT(STR_TO_DATE(Time, "%Y-%m-%d"),"%Y-%m") AS "Month",
SUM(Rate / 800) as kWh
FROM
Log
GROUP BY
DATE_FORMAT(STR_TO_DATE(Time, "%Y-%m-%d"),"%Y-%m"), Time
ORDER BY
STR_TO_DATE(Time, "%Y-%m-%d");
Results looks like :
Month
kWh
2022-01
1700773808
2022-02
1770840497
2022-04
1741656455
2022-05
1738120832
2023-01
1752779938

Related

Hourly counting MySQL

Since few days, I am trying to count records per hour from the MySQL database.
I have a table with a lot of records and I have column DATE and column TIME where in DATE I have the date of the record in the format 2022-05-19, and in the column TIME, I have the time of the record in the format 14:59:38.
What I am trying is to count every single day how many records per hour I have. Something like this:
DATE HOUR PCS
22-05-18 06-07 11
22-05-18 08-09 20
......... ..... ..
....... 21-22 33
I have tried many different ways but no success.
For example:
SELECT 'Date', count(*) FROM `root4`
where
DATE between '2022-05-01' and '2022-05-1' AND
TIME BETWEEN '06:11:05' AND '07:11:05'
Any help is highly evaluated.
I would recommend not using reserved words for columns, as you will have to escape them a lot. https://dev.mysql.com/doc/refman/8.0/en/keywords.html
If you stored TIME as a timestamp, you can extract the hour using the HOUR() function and group by that:
SELECT
`DATE`,
HOUR(`TIME`) AS `HOUR`,
COUNT(1)
FROM your_table
GROUP BY
`DATE`,
HOUR(`TIME`)
If you happened to store it as text you can use REGEXP_SUBSTR to get the hour value from your time string.
SELECT
`DATE`,
CAST(REGEXP_SUBSTR(`TIME`, '[0-9]+') AS UNSIGNED) AS `HOUR`,
COUNT(1)
FROM your_table
GROUP BY
`DATE`,
CAST(REGEXP_SUBSTR(`TIME`, '[0-9]+') AS UNSIGNED)
You can format your HOUR column how you want, like displaying 01-02 instead of 1 by using CONCAT, but this is your basic setup.

MySQL query using unixtime

I have to query a calls.csv table (below) to extract the total calls, total talk seconds and average call seconds:
By day
For the queue 24710 during the month of August 2015
Callid Qid Tm_init Tm_disc
780164900 24710 1422835548 1422835559
780164901 24710 1422835562 1422835687
I arrived at the following query, however, I have been having some difficulties to write the query regarding 'by day' and 'queue 24710 during the month of August 2015':
SELECT
(AVG(`Tm_disc` - `Tm_init`)) AS AVARAGE_CALLS_SECONDS,
(SUM(`Tm_disc` - `Tm_init`)) AS TOTAL_SECONDS_CALLS,
COUNT(`Callid`) AS TOTAL_NUMBER_CALLS
FROM
calls_database.`calls`
Any help, please?
Thank you
You can use FROM_UNIXTIME() to convert unix date to timestamp and then regular datetime functions such as DATE() functions to extract day from the unixtime.
SELECT
(AVG(`Tm_disc` - `Tm_init`)) AS AVARAGE_CALLS_SECONDS,
(SUM(`Tm_disc` - `Tm_init`)) AS TOTAL_SECONDS_CALLS,
COUNT(`Callid`) AS TOTAL_NUMBER_CALLS
FROM
calls
WHERE
Qid=24710
AND
MONTH(FROM_UNIXTIME(Tm_init))=2
AND
YEAR(FROM_UNIXTIME(Tm_init))=2015
GROUP BY DATE(FROM_UNIXTIME(Tm_init))
SQLFiddle: http://sqlfiddle.com/#!9/58dfcc8/9
Then add your filters such as Qid=1234.

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

How can I group data by month, day and hour in mysql?

I have a mysql database that looks like this:
id | userid | timestamp | activity
Timestamp is a datetime data type, I need to get the data grouped by month, day and hour. I am using mysql and php for my scripts.
I am able to do it by month and day with the following query:
$query = "SELECT COUNT(id) as totals FROM security_transactions WHERE YEAR(timestamp) = 2012 GROUP BY MONTH(timestamp), DAY(timestamp)";
I need to do it by month day and hours.
Please help.
Thanks.
You can add , HOUR(TIME(timestamp)) to your group by query providing your column is of DATETIME format
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_hour
Also, from the error messages put in the comments below, it looks like #Aprentice is not using mysql, but I've improved this answer for others looking for mysql.
I have never used mssql, so I can't test this but the following might work to group by nearest hour:
GROUP BY dateadd(hour, datediff(hour, 0, timestamp, 0)
Just take it one step further and use HOUR() as well. You will first need to extract the time portion of the timestamp. But guess what, there is a function for that as well ;)

MySQL Query for getting payments evolution graph during latest 12 months

My app stores payments done by clients. At the end of every month, the total paid that month is calculated and given to owner: I have a payments table that has the following fields (the most important).
id, datepaid, endingdate (actual month's closing date), ammount, type, code, ...
Now, having a year of payments, I've been asked to create a graph of payments evolution (totals) of latest 12 months.
By reading, etc. this is the query I've got, but I don't know how to get the latest 12 months totals (and to get 0 in case no payment was done that month)....
SELECT id, endingdate, datepaid, SUM(ammount) AS total
FROM `sis_payments`
WHERE endingdate >= DATE_SUB( CURDATE( ) , INTERVAL 1 YEAR )
GROUP BY endingdate
I know it may be badly designed, but it's what I was given... any clues? Thanks
You could try GROUP BY YEAR(endingdate), MONTH(endingdate), or something equivalent using DATE_FORMAT. Take a look at the Mysql documentation for DATE_FORMAT.
Also, don't include the date fields (endingdate, datepaid) in the SELECT clause. Instead, use YEAR(endingdate), MONTH(endingdate), just like in GROUP BY.
Getting 0 when there were no payments that month is a little more complicated in SQL. You could handle that in PHP, after running the query.
UPDATE
Example using DATE_FORMAT:
SELECT
DATE_FORMAT(mrendido,'%y-%m') as xyearmonth,
SUM(FORMAT(ammountpaid,2)) AS ammtotal
FROM sis_pyments
WHERE mrendido >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
GROUP BY xyearmonth
ORDER BY xyearmonth ASC