MySQL - All entries with same timestamp in one row - mysql

I recently build my first database with MySQL. I use it to log data from ten different sensors every ten minutes. Each sensor has a unique ID and all sensors are read out at the same time so that ten entries get the same timestamp. The database looks like this:
sensor_id | timestamp | sensor_value |
1 | 2016-06-13 20:40:00 | 19.1 |
2 | 2016-06-13 20:40:00 | 20.1 |
3 | 2016-06-13 20:40:00 | 21.5 |
.
.
.
10 | 2016-06-13 20:40:00 | 18.7 |
1 | 2016-06-13 20:50:00 | 19.4 |
2 | 2016-06-13 20:50:00 | 20.2 |
3 | 2016-06-13 20:50:00 | 22.1 |
.
.
.
10 | 2016-06-13 20:50:00 | 17.9 |
.
.
.
Now I would like to export the data in such a way that I get a row for each timestamp with ten following columns containing the values of the ten sensors:
| 1 | 2 | 3 | ... | 10 |
2016-06-13 20:40:00 | 19.1 | 20.1 | 21.5 | ... | 18.7 |
2016-06-13 20:50:00 | 19.4 | 20.2 | 22.1 | ... | 17.9 |
.
.
.
I tried to use GROUP_CONCAT and almost got what I was looking for. But this gives me all the sensor values in one column as a comma separated list
timestamp | GROUP_CONCAT(sensor_value) |
2016-06-13 20:40:00 | 19.1,20.1,21.5,...,18.7 |
2016-06-13 20:50:00 | 19.4,20.2,22.1,...,17.9 |
.
.
.
Unfortunately, sometimes one of the sensors fails to deliver its value and no entry is added into my database. Therefore, there are sometimes only nine values with the same timestamp. And the comma separated list can not tell me which of the sensors is missing. That is why I need one column per unique sensor ID. Is there a way to achieve this?
I tried to work it out by browsing Stack Overflow, but since I am fairly new to MySQL and databases I did not manage to resolve my problem without posting a new question. If it has been asked and answered before I am sorry and would be happy if someone redirected me in the right direction.
Thanks!

Just use conditional aggregation:
select timestamp,
max(case when sensor_id = 1 then sensor_value end) as sensor_1,
max(case when sensor_id = 2 then sensor_value end) as sensor_2,
. . .
from t
group by timestamp;

Related

Change number of digits displayed

I have some results from the tabulate command in Stata:
However, these appear with numbers that are too detailed such as 0.4988995.
I want to change the number of digits in the output. For example, 0.0499 instead of 0.4988995.
Is there any way to reduce the number of digits displayed?
It is not necessary to generate new variables or use other commands such as tabdisp. The tabulate command respects a variable's format.
Consider the following toy example:
sysuse auto, clear
format mpg
variable name display format
-----------------------------
mpg %8.0g
-----------------------------
tabulate rep78 foreign, summarize(mpg) nofreq
Means and Standard Deviations of Mileage (mpg)
Repair |
Record | Car type
1978 | Domestic Foreign | Total
-----------+----------------------+----------
1 | 21 . | 21
| 4.2426407 . | 4.2426407
-----------+----------------------+----------
2 | 19.125 . | 19.125
| 3.7583241 . | 3.7583241
-----------+----------------------+----------
3 | 19 23.333333 | 19.433333
| 4.0856221 2.5166115 | 4.1413252
-----------+----------------------+----------
4 | 18.444444 24.888889 | 21.666667
| 4.5856055 2.7131368 | 4.9348699
-----------+----------------------+----------
5 | 32 26.333333 | 27.363636
| 2.8284271 9.367497 | 8.7323849
-----------+----------------------+----------
Total | 19.541667 25.285714 | 21.289855
| 4.7533116 6.3098562 | 5.8664085
Consequently, you just need to set the desired format beforehand:
format mpg %8.3g
tabulate rep78 foreign, summarize(mpg) nofreq
Means and Standard Deviations of Mileage (mpg)
Repair |
Record | Car type
1978 | Domestic Foreign | Total
-----------+----------------------+----------
1 | 21 . | 21
| 4.24 . | 4.24
-----------+----------------------+----------
2 | 19.1 . | 19.1
| 3.76 . | 3.76
-----------+----------------------+----------
3 | 19 23.3 | 19.4
| 4.09 2.52 | 4.14
-----------+----------------------+----------
4 | 18.4 24.9 | 21.7
| 4.59 2.71 | 4.93
-----------+----------------------+----------
5 | 32 26.3 | 27.4
| 2.83 9.37 | 8.73
-----------+----------------------+----------
Total | 19.5 25.3 | 21.3
| 4.75 6.31 | 5.87
There is not a single switch to do this, just various devices.
Here is one:
. sysuse auto, clear
(1978 Automobile Data)
. tabulate for rep78, summarize(mpg) nost nofreq
Means of Mileage (mpg)
| Repair Record 1978
Car type | 1 2 3 4 5 | Total
-----------+-------------------------------------------------------+----------
Domestic | 21 19.125 19 18.444444 32 | 19.541667
Foreign | . . 23.333333 24.888889 26.333333 | 25.285714
-----------+-------------------------------------------------------+----------
Total | 21 19.125 19.433333 21.666667 27.363636 | 21.289855
. egen mean = mean(mpg), by(for rep78)
. tabdisp for rep78, c(mean) format(%2.1f)
----------------------------------------------
| Repair Record 1978
Car type | 1 2 3 4 5 .
----------+-----------------------------------
Domestic | 21.0 19.1 19.0 18.4 32.0 23.3
Foreign | 23.3 24.9 26.3 14.0
----------------------------------------------
Note further that tabstat yields summarize-like results but with an option format().

mysql give one wrong timediff out of 20 right

I have the following query:
SELECT `Time`,
`Resolution`,
HOUR(TIMEDIFF(`Resolution`,`Time`)),
TIMEDIFF(`Resolution`,`Time`),
datediff(`Resolution`,`Time`)
FROM Cases;
In order to debug, I add the TIMEDIFF without the HOUR before, just to see if the result is different. I use datediff to double check.
The result of the query is:
+---------------------+---------------------+-------------------------------------+-------------------------------+-------------------------------+
| Time | Resolution | HOUR(TIMEDIFF(`Resolution`,`Time`)) | TIMEDIFF(`Resolution`,`Time`) | datediff(`Resolution`,`Time`) |
+---------------------+---------------------+-------------------------------------+-------------------------------+-------------------------------+
| 2017-01-10 13:35:00 | 2017-01-24 10:52:00 | 333 | 333:17:00 | 14 |
| 2017-01-12 15:53:00 | 2017-02-21 16:06:00 | 838 | 838:59:59 | 40 |
| 2017-01-18 09:19:00 | 2017-01-18 13:39:00 | 4 | 04:20:00 | 0 |
| 2017-01-23 09:00:00 | 2017-01-23 15:08:00 | 6 | 06:08:00 | 0 |
| 2017-01-24 08:49:00 | 2017-02-20 14:34:00 | 653 | 653:45:00 | 27 |
Actually, it delivers more lines, but the relevant line is the 2 result - 838 hours, which translates to 34.91 days, let's say 35, but the DATEDIFF give 40 and when you do yourself the calculation it is 40 days! 12th Jan to 21st Feb.
All other 21 results are correct.
Any idea why? A bug in mysql?
All responses are highly appreciated.
Use
TIMESTAMPDIFF(HOUR,`Time`, `Resolution`)
instead.
It also negates the need to use HOUR().
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampdiff
The result returned by TIMEDIFF() is limited to the range allowed for TIME values. https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timediff
TIME values may range from -838:59:59 to 838:59:59. https://dev.mysql.com/doc/refman/5.5/en/time.html
So you're getting the maximum possible value.

SQL - select x entries within a timespan

I'm creating a database (in MySQL) with a table of measurements. For each measurement I want to store the DateTime it came in. For showing plots within an app for different intervals (measurements of the day/week/month/year) I want sample the data points I have, so I can return e. g. 30 data points for the whole year as well as for the day/hour. This is the same as done with stock price graphs:
stock price plot for 1 day
vs
stock price plot for 1 month
As you can see, the amount of data points is the same in both pictures.
So how can I select x entries within a timespan in MySQL via SQL?
My data looks like this:
+====+====================+=============+==========+
| id | datetime | temperature | humidity |
+====+====================+=============+==========+
| 1 | 1-15-2016 00:30:00 | 20 | 40 |
+----+--------------------+-------------+----------+
| 2 | 1-15-2016 00:35:00 | 19 | 41 |
+----+--------------------+-------------+----------+
| 3 | 1-15-2016 00:40:00 | 20 | 40 |
+----+--------------------+-------------+----------+
| 4 | 1-15-2016 00:45:00 | 20 | 42 |
+----+--------------------+-------------+----------+
| 5 | 1-15-2016 00:50:00 | 21 | 42 |
+----+--------------------+-------------+----------+
| 6 | 1-15-2016 00:55:00 | 20 | 43 |
+----+--------------------+-------------+----------+
| 7 | 1-15-2016 01:00:00 | 21 | 43 |
+====+====================+=============+==========+
Let's say, I always want two data points (in reality a lot more). So for the last half hour I want the database to return data point 1 and 4, for the last ten minutes I want it to return 6 and 7.
Thanks for helping!
PS: I'm sorry for any errors in my English
OK, assuming a very simple systematic approach, you can get the first and last entry for any defined period:
select *
from table
where mydatetime =
(select
max(mydatetime)
from table
where mydatetime between '2017-03-01' and '2017-03-15'
)
OR mydatetime =
(select
min(mydatetime)
from table
where mydatetime between '2017-03-01' and '2017-03-15'
)
I believe your answer can be found at the following location:
https://stackoverflow.com/a/1891796/7176046
If you are looking to filter out any items not within your date/time your query would use:
Select * from table where Date/Time is (What you want to sort by)

mysql 5.5.50 Calculate one day multiple events to one

I have a problem with my thinking and I must ask someone to help.
I create simply working time tracking system and I can manage all other things with that code, but I cannot now figure out how I can calculate following data.
Fist, I have couple tables and one store four things.
index | who | timestamp | what
1 | 1 | 2016-09-21 08:00:00 | Work
2 | 2 | 2016-09-21 08:01:00 | Work
3 | 1 | 2016-09-21 10:00:00 | Bin
4 | 2 | 2016-09-21 10:00:00 | Bin
5 | 1 | 2016-09-21 10:15:00 | Bout
6 | 2 | 2016-09-21 10:17:00 | Bout
7 | 2 | 2016-09-21 13:00:00 | Bin
8 | 1 | 2016-09-21 13:00:00 | Bin
9 | 1 | 2016-09-21 13:30:00 | Bout
10 | 2 | 2016-09-21 13:30:00 | Bout
11 | 2 | 2016-09-21 15:58:00 | Home
12 | 1 | 2016-09-21 16:05:00 | Home
I can nicely calculate times between Work and Home and got right value to the right person.
But I'm stuck now with those break times.
I need calculate all possible breaks together per person and that way get a total time what is spend to breaks per person.
So I need something like following answer when ask person 1 info:
Who | Time | Breaktime | Working time
1 | 08:05:00 | 00:45:00 | 07:20:00
Or maybe all persons can came to same page when ask specific day...
Who | Time | Breaktime | Working time
1 | 08:05:00 | 00:45:00 | 07:20:00
2 | 07:57:00 | 00:47:00 | 07:10:00
There is always pairs with events. Work -> Home and Bin -> Bout.
And yes, there is much more persons and could be much more brake times per person.
That might be a bad presentation, sorry about that (NooB). I hope I give that much information as someone can help. But ask if there is something to ask.
That is code what I use when I solve one day total time at working place.
SELECT TIMEDIFF(
(SELECT timestamp FROM `stamps` WHERE (who like '1' and DATE (timestamp) like '2016-09-21' and what like 'Home')),
(SELECT timestamp FROM `stamps` WHERE (who like '1' and DATE (timestamp) like '2016-09-21' and what like 'Work'))
)
But I cannot use it with multiple events.
That is what I found. Maybe not nice, but it works =).
$break = mysqli_query($conn,"SELECT what, timestamp FROM stamps WHERE (who like '$id' and DATE (timestamp) like '$day' and what like 'B%') ORDER BY timestamp");
while($row = mysqli_fetch_array($break))
{
if ( $row['what'] == "Bin" )
$start = strtotime( $row['timestamp'] );
else { $stop = strtotime( $row['timestamp'] );
$hours += ( $stop - $start );
}
}
$btime = gmdate('H:i:s', floor($hours));
$btime gives 00:00:00 style result.

mysql split a string in a where clause

I have an event system and for my repeat events I am using a cron like system.
Repeat Event:
+----+----------+--------------+
| id | event_id | repeat_value |
+----+----------+--------------+
| 1 | 11 | *_*_* |
| 2 | 12 | *_*_2 |
| 3 | 13 | *_*_4/2 |
| 4 | 14 | 23_*_* |
| 5 | 15 | 30_05_* |
+----+----------+--------------+
NOTE: The cron value is day_month_day of week
Event:
+----+------------------------+---------------------+---------------------+
| id | name | start_date_time | end_date_time |
+----+------------------------+---------------------+---------------------+
| 11 | Repeat daily | 2014-04-30 12:00:00 | 2014-04-30 12:15:00 |
| 12 | Repeat weekly | 2014-05-06 12:00:00 | 2014-05-06 13:00:00 |
| 13 | Repeat every two weeks | 2014-05-08 12:45:00 | 2014-05-08 13:45:00 |
| 14 | Repeat monthly | 2014-05-23 15:15:00 | 2014-05-23 16:00:00 |
| 15 | Repeat yearly | 2014-05-30 07:30:00 | 2014-05-30 10:15:00 |
+----+------------------------+---------------------+---------------------+
Anyway I have a query to select the events:
SELECT *
FROM RepeatEvent
JOIN `Event`
ON `Event`.`id` = `RepeatEvent`.`event_id`
That produces:
+----+----------+--------------+----+------------------------+---------------------+---------------------+
| id | event_id | repeat_value | id | name | start_date_time | end_date_time |
+----+----------+--------------+----+------------------------+---------------------+---------------------+
| 1 | 11 | *_*_* | 11 | Repeat daily | 2014-04-30 12:00:00 | 2014-04-30 12:15:00 |
| 2 | 12 | *_*_2 | 12 | Repeat weekly | 2014-05-06 12:00:00 | 2014-05-06 13:00:00 |
| 3 | 13 | *_*_4/2 | 13 | Repeat every two weeks | 2014-05-08 12:45:00 | 2014-05-08 13:45:00 |
| 4 | 14 | 23_*_* | 14 | Repeat monthly | 2014-05-23 15:15:00 | 2014-05-23 16:00:00 |
| 5 | 15 | 30_05_* | 15 | Repeat yearly | 2014-05-30 07:30:00 | 2014-05-30 10:15:00 |
+----+----------+--------------+----+------------------------+---------------------+---------------------+
However, I want to select events within a month. I will only have certain conditions: daily, weekly, every two weeks, month and yearly.
I want to put in my where clause a way to divide the string of the repeat value and if it fits any of the following conditions to show it as a result (repeatEvent is row that is being interrogated, search is the date being looked for):
array(3) = string_divide(repeat_value, '_')
daily = array(0)
monthy = array(1)
dayOfWeek = array(2)
if(daily == '*' && month == '*' && dayOfWeek == '*') //returns all the daily events as they will happen
return repeatEvent
if(if(daily == '*' && month == '*' && dayOfWeek == search.dayOfWeek) //returns all the events on specific day
return repeatEvent
if(daily == search.date && month == '*' && dayOfWeek == '*') //returns all the daily events as they will happen
return repeatEvent
if (contains(dayOfWeek, '/'))
array(2) = string_divide(dayOfWeek,'/')
specificDayOfWeek = array(0);
if(specificDayOfWeek == repeatEvent.start_date.dayNumber)
if(timestampOf(search.timestamp)-timestampOf(repeatEvent.start_date)/604800 == (0 OR EVEN)
return repeatEvent
if(daily == search.date && month == search.month && dayOfWeek == '*') //returns a single yearly event (shouldn't often crop up)
return repeatEvent
//everything else is either an unknown format of repeat_value or not an event on this day
To summarise I want to run a query in which the repeat value is split in the where clause and I can interrogate the split items. I have looked at cursors but the internet seems to advise against them.
I could process the results of selecting all the repeat events in PHP, however, I imagine this being very slow.
Here is what I would like to see if looking at the month of April:
+----------+--------------+----+------------------------+---------------------+---------------------+
| event_id | repeat_value | id | name | start_date_time | end_date_time |
+----------+--------------+----+------------------------+---------------------+---------------------+
| 11 | *_*_* | 11 | Repeat daily | 2014-04-30 12:00:00 | 2014-04-30 12:15:00 |
+----------+--------------+----+------------------------+---------------------+---------------------+
Here is what I would like to see if looking at the month of May
+----------+--------------+----+------------------------+---------------------+---------------------+
| event_id | repeat_value | id | name | start_date_time | end_date_time |
+----------+--------------+----+------------------------+---------------------+---------------------+
| 11 | *_*_* | 11 | Repeat daily | 2014-04-30 12:00:00 | 2014-04-30 12:15:00 |
| 12 | *_*_2 | 12 | Repeat weekly | 2014-05-06 12:00:00 | 2014-05-06 13:00:00 |
| 13 | *_*_4/2 | 13 | Repeat every two weeks | 2014-05-08 12:45:00 | 2014-05-08 13:45:00 |
| 14 | 23_*_* | 14 | Repeat monthly | 2014-05-23 15:15:00 | 2014-05-23 16:00:00 |
| 15 | 30_05_* | 15 | Repeat yearly | 2014-05-30 07:30:00 | 2014-05-30 10:15:00 |
+----------+--------------+----+------------------------+---------------------+---------------------+
Here is what I would like to see if looking at the month of June
+----------+--------------+----+------------------------+---------------------+---------------------+
| event_id | repeat_value | id | name | start_date_time | end_date_time |
+----------+--------------+----+------------------------+---------------------+---------------------+
| 11 | *_*_* | 11 | Repeat daily | 2014-04-30 12:00:00 | 2014-04-30 12:15:00 |
| 12 | *_*_2 | 12 | Repeat weekly | 2014-05-06 12:00:00 | 2014-05-06 13:00:00 |
| 13 | *_*_4/2 | 13 | Repeat every two weeks | 2014-05-08 12:45:00 | 2014-05-08 13:45:00 |
| 14 | 23_*_* | 14 | Repeat monthly | 2014-05-23 15:15:00 | 2014-05-23 16:00:00 |
+----------+--------------+----+------------------------+---------------------+---------------------+
You could put a bandaid on this, but no one would be doing you any favors to tell you that that is the answer.
If your MySQL database can be changed I would strongly advise you to split your current column with underscores day_month_day of year to three separate columns, day, month, and day_of_year. I would also advise you to change your format to be INT rather than VARCHAR. This will make it faster and MUCH easier to search and parse, because it is designed in a way that doesn't need to be translated into computer language through complicated programs... It is most of the way there already.
Here's why:
Reason 1: Your Table is not Optimized
Your table is not optimized and will be slowed regardless of what you choose to do at this stage. SQL is not built to have multiple values in one column. The entire point of an SQL database is to split values into different columns and rows.
The advantage to normalizing this table is that it will be far quicker to search it, and you will be able to build queries in MySQL. Take a look at Normalization. It is a complicated concept, but once you get it you will avoid creating messy and complicated programs.
Reason 2: Your Table could be tweaked slightly to harness the power of computer date/time functions.
Computers follow time based on Unix Epoch Time. It counts seconds and is always running in your computer. In fact, computers have been counting this since, as the name implies, the first Unix computer was ever switched on. Further, each computer and computer based program/system, has built in, quick date and time functions. MySQL is no different.
I would also recommend also storing all of these as integers. repeat_doy (day of year) can easily be a smallint or at least a standard int, and instead of putting a month and day, you can put the actual 1-365 day of the year. You can use DAY_OF_YEAR(NOW()) to input this into MySQL. To pull it back out as a date you can use MAKEDATE(YEAR(NOW),repeat_doy). Instead of an asterisk to signify all, you can either use 0's or NULL.
With a cron like system you probably will not need to do that sort of calculation anyway.
Instead, it will probably be easier to just measure the day of year elsewhere (every computer and language can do this. In Unix it is just date "%j").
Solution
Split your one repeat_value into three separate values and turn them all into integers based on UNIX time values. Day is 1-7 (or 0-6 for Sunday to Saturday), Month is 1-12, and day of year is 1-365 (remember, we are not including 366 because we are basing our year on an arbitrary non-leap year).
If you want to pull information in your SELECT query in your original format, it is much easier to use concat to merge the three columns than it is to try to search and split on one column. You can also easily harness built in MySQL functions to quickly turn what you pull into real, current, days, without a bunch of effort on your part.
To implement it in your SQL database:
+----+----------+--------------+--------------+------------+
| id | event_id | repeat_day | repeat_month | repeat_doy |
+----+----------+--------------+--------------+------------+
| 1 | 11 | * | * | * |
| 2 | 12 | * | * | 2 |
| 3 | 13 | * | * | 4/2 |
| 4 | 14 | 23 | * | * |
| 5 | 15 | 30 | 5 | * |
+----+----------+--------------+--------------+------------+
Now you should be able to build one query to get all of this data together regardless of how complicated your query. By normalizing your table, you will be able to fully harness the power of relational databases, without the headaches and hacks.
Edit
Hugo Delsing made a great point in the comments below. In my initial example I provided a fix to leap years for day_of_year in which I chose to ignore Feb 29. A much better solution removes the need for a fix. Split day_of_year to month and day with a compound index. He also has a suggestion about weeks and number of weeks, but I will just recommend you read it for more details.
Try to write where condition using this:
substring_index(repeat_value,'_', 1)
instead of daily
substring_index(substring_index(repeat_value,'_', -2), '_', 1)
instead of monthly
and
substring_index(substring_index(repeat_value,'_', -1), '_', 1)
instead of dayOfWeek
I think you are overthinking the problem if you only want the events per month and not per day. Assuming that you always correctly fill the repeat_value, the query is very basic.
Basically all event occur every month where the repeat_value is either LIKE '%_*_%' or LIKE '%_{month}_%'.
Since you mentions PHP I'm assuming you are building the query in PHP and thus I used the same.
<?php
function buildQuery($searchDate) {
//you could/should do some more checking if the date is valid if the user provides the string
$searchDate = empty($searchDate) ? date("Y-m-d") : $searchDate;
$splitDate = explode('-', $searchDate);
$month = $splitDate[1];
//Select everything that started after the searchdate
//the \_ is because else the _ would match any char.
$query = 'SELECT *
FROM RepeatEvent
JOIN `Event`
ON `Event`.`id` = `RepeatEvent`.`event_id`
WHERE `Event`.`start_date_time` < \''.$searchDate.'\'
AND
(
`RepeatEvent`.`repeat_value` LIKE \'%\_'.$month.'\_%\'
OR `RepeatEvent`.`repeat_value` LIKE \'%\_*\_%\'
)
';
return $query;
}
//show querys for all months on current day/year
for ($month = 1; $month<=12; $month++) {
echo buildQuery(date('Y-'.$month.'-d')) . '<hr>';
}
?>
Now if the repeat_value could be wrong, you could add a simple regex check to make sure the value is always like *_*_* or *_*_*/*
You can use basic regular expressions in MySQL:
http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html
For a monthly event in May (first day) you can use a pattern like this (not tested):
[0-9\*]+\_[5\*]\_1
You can generate this pattern via PHP