get avg data every 15 min - mysql

I'm new to tsql and use mysql db. Seen an example code(at below) to get data from database every 2 hour:
SELECT date(`dateTime`) dateDay, 2*floor(date_format(`dateTime`,'%H')/2) dateHour,
avg(channel1), avg(channel2), avg(channel3)
FROM `Table`
WHERE `id` =1
AND `dateTime` >= '2011-10-15 00:00:01'
AND `dateTime` <= '2011-10-17 23:59:59'
Then I did few changes based on the above code to get data every 15 minutes:
SELECT date(`dateTime`) dateDay, 15*floor(date_format(`dateTime`,'%i')/15) dateHour,
avg(channel1), avg(channel2), avg(channel3)
FROM `Table`
WHERE `id` =1
AND `dateTime` >= '2011-10-15 00:00:01'
AND `dateTime` <= '2011-10-17 23:59:59'
group by date(`dateTime`), 15*floor(date_format(`dateTime`,'%i')/15)
However the query is not correct.
My questions are:
How to amend the query to get data every 15 min?
How to write sql query to get all data as well? and dateDay and dateHour columns need to be here.

1: every 15 minutes:
SELECT date(dateTime) dateDay, 2*floor(date_format(dateTime,'%H')/2) dateHour,
avg(channel1), avg(channel2), avg(channel3)
-->
SELECT date(`dateTime`) dateDay
,CONCAT( 2*floor(date_format(`dateTime`,'%H')/2), ':', 15*FLOOR(DATE_FORMAT(`dateTime`, '%i')/15)) dateQuarter
,avg(channel1), avg(channel2), avg(channel3)
FROM `Table`
WHERE `id` =1
AND `dateTime` >= '2011-10-15 00:00:01'
AND `dateTime` <= '2011-10-17 23:59:59'
GROUP BY 1,2;
2: all data. I wasn't really sure what you wanted. but here's every row with hour:minute in dateHour field.
SELECT date(`dateTime`) dateDay,
,DATE_FORMAT(`dateTime`, '%H:%i') dateHour,
FROM `Table`
WHERE `id` =1
AND `dateTime` >= '2011-10-15 00:00:01'
AND `dateTime` <= '2011-10-17 23:59:59'

Related

MySQL Full Group by

Since my web-host has updated the MySQL server version, my old SQL Query is not working anymore:
select COUNT(ID) AS Anzahl,
DAY(STR_TO_DATE(created_at, '%Y-%m-%d')) AS Datum
from `leads`
where `created_at` >= 2018-02-01
and `created_at` <= 2018-02-15
and `shopID` = 20
group by DAY(created_at)
order by DAY(created_at) asc
That means, I have to create a full group by query. I already have read this article but I don't really get it.
I should name all columns which are unique
Thats what I don't get. If I want to count the ID, I cannot create a group by ID query because in this case my count would always be 1. Could anybody please explain to me how full group by works and how my statement would like with a full group by statement?
Just use the same expression in the select as in the group by:
select COUNT(ID) AS Anzahl, DAY(created_at) AS Datum
from `leads` l
where `created_at` >= '2018-02-01' and
`created_at` <= '2018-02-15' and
`shopID` = 20
group by DAY(created_at)
order by DAY(created_at) asc;
You also need single quotes around the date constants.
Your select and group by columns doesn't match. You should make them same. Try below query:
select COUNT(ID) AS Anzahl,
DAY(STR_TO_DATE(created_at, '%Y-%m-%d')) AS Datum
from `leads`
where `created_at` >= 2018-02-01
and `created_at` <= 2018-02-15
and `shopID` = 20
group by Datum
order by Datum asc

mySQL multiple data resolution query

I'm trying to select data at two different resolutions based on data points per unit of time. Right now I'm just running two queries and joining them with a UNION. To get the number resolutions I want I'm using this to achieve 1 data point per minute:
GROUP BY UNIX_TIMESTAMP(`datetime`) DIV 60
Just wondering if there is a more efficient way to do this?
SELECT (UNIX_TIMESTAMP(`datetime`)*1000) as `dt`, `value1`, `value2`
FROM `table`
WHERE `datetime` BETWEEN '2017-01-01' AND '2018-01-01'
GROUP BY UNIX_TIMESTAMP(`datetime`) DIV 240
UNION
SELECT (UNIX_TIMESTAMP(`datetime`)*1000) as `dt`, `value1`, `value2`
FROM `table`
WHERE `datetime` BETWEEN '2017-01-01' AND '2018-01-01'
AND TIME(`datetime`) BETWEEN TIME('12:00:00') AND TIME('13:00:00')
GROUP BY UNIX_TIMESTAMP(`datetime`) DIV 60
ORDER BY `dt` ASC;
Here's an alternative I came across. This one seems a little quicker and returns the actual values for the times selected instead of mySQL just picking one from each time group.
On this table datetime is an index.
SELECT a.`datetime`, a.`value1`, a.`value2`
FROM `table` a
INNER JOIN
(
SELECT `datetime`
FROM `table`
WHERE DATE(`datetime`) BETWEEN '2017-01-01' AND '2018-01-01'
GROUP BY UNIX_TIMESTAMP(`datetime`) DIV 240
UNION
SELECT `datetime`
FROM `table`
WHERE DATE(`datetime`) BETWEEN '2017-01-01' AND '2018-01-01'
AND TIME(`datetime`) BETWEEN '12:00:00' AND '13:00:00'
GROUP BY UNIX_TIMESTAMP(`datetime`) DIV 60
ORDER BY `datetime`
) b on a.`datetime` = b.`datetime`;

MySQL Subquery with datetime comparison from main query values

I am trying to do what seems like a simple query.. I have a query which works fine until I try to add a subquery to the select clause. I am trying to add a column by querying a second table with the dates I get from the first. I don't know if a join might be better. If you look at my first sample it returns every record in my second table instead of using the date range from the outer select statement.
SELECT `sales`.`date` as 'newdate', `sales`.`material`,
`customer_logs`.`name`, `sales`.`billingqty` ,
(select count(*) from iis_logs where datetime > (select
Date_add(date_format(newdate, "%Y-%m-%d 00:00:00"), interval - 1 day))
and datetime < date_format(newdate, '%Y-%m-%d 00:00:00' and url like
CONCAT('%',material,'%') limit 1) as tr
FROM `sales`
JOIN `customer_logs` ON `customer_logs`.`customer_number` =
`sales`.`soldtopt`
WHERE `date` >= '2017-09-01'
AND `date` <= '2017-09-30'
ORDER BY `date` DESC
LIMIT 10;
If I just type the string as a date in like this it returns within a second:
SELECT `sales`.`date` as 'newdate', `sales`.`material`,
`customer_logs`.`name`, `sales`.`billingqty` ,
(select count(*) from iis_logs where datetime > '2017-09-01 00:00:00'
and datetime < '2017-09-03 00:00:00' and url like
CONCAT('%',material,'%') limit 1) as tr
FROM `sales`
JOIN `customer_logs` ON `customer_logs`.`customer_number` =
`sales`.`soldtopt`
WHERE `date` >= '2017-09-01'
AND `date` <= '2017-09-30'
ORDER BY `date` DESC
LIMIT 10;
It is not taking the value of newdate I am trying to get in select statement, instead it is returning every row in iis_logs table...
This looks like a perfect candidate for a join. FWIW, mysql query optimizer typically does better on joins that subqueries anyway.

How to union two ordered queries in the same table

I have events table with columns
'title',
'description',
'start_date',
'end_date'.
I want to get ordered list live and future events, depends on 'start_date' and 'end_date'.
I try
(
select *
from `events`
where `start_date` < NOW() and `end_date` > NOW()
order by `start_date` desc
)
union all
(
select *
from `events`
where `start_date` > NOW()
order by `start_date` desc)
but result have not that ordering which I want. I want at first ordered list by start_date live events after that ordered list by start_date future events.
I think you do not need union in this one.
Just put a OR condition in your basic query.
Then, to split the result into "this one is live" and "this one is future" you can use a flag
SELECT *, start_date < NOW() AS flag
FROM `events`
WHERE (`start_date` < NOW() and `end_date` > NOW())
OR `start_date` > NOW()
ORDER BY flag DESC, start_date
Nota : the DESC is here to show you you want live before future event. Otherwise just put ASC.
Try this:
select * from (
(
select start_date, end_date, 'Live' as event_type
from `events`
where `start_date` < NOW() and `end_date` > NOW()
)
union
(
select start_date, end_date, 'Future' as event_type
from `events`
where `start_date` > NOW() ) ) a
ORDER BY event_type desc
, case when event_type = 'Live' then start_date end desc
, case when event_type = 'Future' then start_date end asc;
Why can't you just select all events ordered by start_date?
select *
from `events`
where (`start_date` < NOW() AND `end_date` > NOW())
or (`start_date` > NOW())
order by `start_date` desc
Anyway live events will be first, then future events

MySQL Top10 for 7 Days Ago

I have a problem...
I search in this site for any solutions... I tried them but on one workout :(
So I'm trying to get the top 10 results for 7 days ago by views...
So I try codes like that:
SELECT * FROM `data`
WHERE cast(`date` as DATE) BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY)
AND CURDATE() ORDER by `viewed` DESC LIMIT 0,10
or
SELECT * FROM `data`
WHERE `date` > (NOW() - INTERVAL 7 DAY)
ORDER by `viewed` DESC LIMIT 0,10
or
SELECT * FROM `data`
WHERE DATE(`date`) = DATE_SUB(NOW(), INTERVAL 7)
ORDER by `viewed` DESC LIMIT 0,10
or
SELECT * FROM `data`
WHERE `date` >= SUBDATE(NOW(), INTERVAL 7 DAY)
ORDER by `viewed` DESC LIMIT 0,10
I try them with any combination with NOW() TIME() DATE() CURDATE() SUBDATE() SUBTIME() DATE_SUB() etc... but nothing works :( I really don't know what is the problem. I submit the date to database with time() function(PHP) can it be that the problem?
Try this:
SELECT date, viewed FROM data
WHERE date BETWEEN UNIX_TIMESTAMP(NOW() - INTERVAL 7 day) AND UNIX_TIMESTAMP(NOW())
ORDER BY viewed DESC
LIMIT 0,10;
And this if you want the date and time displayed.
SELECT FROM_UNIXTIME(date), viewed FROM data
WHERE date BETWEEN UNIX_TIMESTAMP(NOW() - INTERVAL 7 day) AND UNIX_TIMESTAMP(NOW())
ORDER BY viewed DESC
LIMIT 0,10
Sample data:
CREATE TABLE data
(
id int auto_increment primary key,
date varchar(10),
viewed int
);
INSERT INTO data
(date, viewed)
VALUES
(1392749561, 50),
(1392749950, 25),
(1392850985, 10),
(1393023471, 75),
(1392936840, 100);
SQLFiddle demo