I'm working on a site that requires me to display a graph of the average number per day of a user input. I have a SQL query already that returns this info to me:
SELECT sum(number)/count(number) as average, date FROM stats WHERE * GROUP BY date
This gives me the result I am looking for, but the result is given with three decimals precision. I want to round of this number. I could do it in PHP or my template engine, of course, but I was curious if there was a way to do this all in the database.
Is there a way to cast an output as an integer (in MySQL)?
SELECT
CAST(sum(number)/count(number) as UNSIGNED) as average,
date
FROM stats
WHERE *
GROUP BY date
The valid types for a CAST in MySQL are as follows
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
So you could use
SELECT CAST(sum(number)/count(number) AS UNSIGNED) as average...
Or SIGNED if the SUM part can ever add up to a negative number.
Use the DIV operator.
mysql> SELECT 5 DIV 2;
-> 2
Integer division. Similar to FLOOR(), but is safe with BIGINT values. Incorrect results may occur for noninteger operands that exceed BIGINT range.
how about using MySQL FORMAT Function?
mysql> SELECT FORMAT(12345.123456, 4);
+-------------------------+
| FORMAT(12345.123456, 4) |
+-------------------------+
| 12,345.1235 |
+-------------------------+
1 row in set (0.00 sec)
mysql> SELECT FORMAT(12345.123456, 0);
+-------------------------+
| FORMAT(12345.123456, 0) |
+-------------------------+
| 12,345 |
+-------------------------+
1 row in set (0.00 sec)
SELECT convert(int, sum(number)/count(number)) as average,
date
FROM stats
WHERE * GROUP BY date
or
SELECT
CAST(sum(number)/count(number) as INT) as average,
date
FROM stats
WHERE *
GROUP BY date
User mysql function round()
Example round(23.33) will return 23 in msyql.
Your example query will be updated to
SELECT round(sum(number)/count(number)) as average, date FROM stats WHERE * GROUP BY date
Related
Actually i am using MySql 5.6.4 version.But the problem is that MySQL retrieves and displays TIME values in 'hh:mm:ss' format (or 'hhh:mm:ss' format for large hours values).
TIME values may range from '-838:59:59' to '838:59:59'. The hours part may be so large because the TIME type can be used not only to represent a time of day (which must be less than 24 hours), but also elapsed time or a time interval between two events (which may be much greater than 24 hours, or even negative).
I want to restrict TIME data type in mysql 5.6.4 version to hold only till 24:00:00 hrs, so if will insert the time which is greater than 24:00:00 then it will show error message.
I have googled a lot for this but i didn'yt find anything although i am bit confused... I just want to know How can i do it?
Insert into exp1.mock_table (reviewTime, created_dt) VALUES ('37:00:00', NOW());
Insert into exp1.mock_table (reviewTime, created_dt) VALUES ('22:01:53', NOW());
alter table exp1.mock_table modify reviewTime time(0) , add check (extract(hour from reviewTime) between 0 and 24);
If you are using MySQL 8+, then you may handle this using check constraints when you define your table:
CREATE TABLE mock_table (
reviewTime time CHECK (HOUR(time) < 24)
created_dt datetime
);
Technically a 24 hour day doesn't support 24:00:00, because 23:59:59 automatically wraps around to 00:00:00 of the next day.
Not sure if this is what #strawberry had in mind but you could test the time and force burst it
drop table if exists t;
create table t
(ts time);
insert into t values (if('20:00:00' > '23:59:59','840:00:00','20:00:00'));
Query OK, 1 row affected (0.02 sec)
insert into t values (if('37:00:00' > '23:59:59','840:00:00','820:00:00'));
ERROR 1292 (22007): Incorrect time value: '840:00:00' for column 'ts' at row 1
select * from t;
+----------+
| ts |
+----------+
| 20:00:00 |
+----------+
1 row in set (0.00 sec)
Consider the following:
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table (id SERIAL PRIMARY KEY, t TIME NOT NULL);
INSERT INTO my_table (t) SELECT '22:23:00' FROM (SELECT 1) n WHERE TIME_TO_SEC('22:23:00') BETWEEN 0 AND 86400;
INSERT INTO my_table (t) SELECT '212:23:00' FROM (SELECT 1) n WHERE TIME_TO_SEC('212:23:00') BETWEEN 0 AND 86400;
SELECT * FROM my_table;
+----+----------+
| id | t |
+----+----------+
| 1 | 22:23:00 |
+----+----------+
I want to convert a timestamp in MySQL to a date.
I would like to format the user.registration field into the text file as a yyyy-mm-dd.
Here is my SQL:
$sql = requestSQL("SELECT user.email,
info.name,
FROM_UNIXTIME(user.registration),
info.news
FROM user, info
WHERE user.id = info.id ", "export members");
I also tried the date conversion with:
DATE_FORMAT(user.registration, '%d/%m/%Y')
DATE(user.registration)
I echo the result before to write the text file and I get :
email1;name1;DATE_FORMAT(user.registration, '%d/%m/%Y');news1
email2;name2;news2
How can I convert that field to date?
DATE_FORMAT(FROM_UNIXTIME(`user.registration`), '%e %b %Y') AS 'date_formatted'
To just get a date you can cast it
cast(user.registration as date)
and to get a specific format use date_format
date_format(registration, '%Y-%m-%d')
SQLFiddle demo
Convert timestamp to date in MYSQL
Make the table with an integer timestamp:
mysql> create table foo(id INT, mytimestamp INT(11));
Query OK, 0 rows affected (0.02 sec)
Insert some values
mysql> insert into foo values(1, 1381262848);
Query OK, 1 row affected (0.01 sec)
Take a look
mysql> select * from foo;
+------+-------------+
| id | mytimestamp |
+------+-------------+
| 1 | 1381262848 |
+------+-------------+
1 row in set (0.00 sec)
Convert the number to a timestamp:
mysql> select id, from_unixtime(mytimestamp) from foo;
+------+----------------------------+
| id | from_unixtime(mytimestamp) |
+------+----------------------------+
| 1 | 2013-10-08 16:07:28 |
+------+----------------------------+
1 row in set (0.00 sec)
Convert it into a readable format:
mysql> select id, from_unixtime(mytimestamp, '%Y %D %M %H:%i:%s') from foo;
+------+-------------------------------------------------+
| id | from_unixtime(mytimestamp, '%Y %D %M %H:%i:%s') |
+------+-------------------------------------------------+
| 1 | 2013 8th October 04:07:28 |
+------+-------------------------------------------------+
1 row in set (0.00 sec)
If the registration field is indeed of type TIMESTAMP you should be able to just do:
$sql = "SELECT user.email,
info.name,
DATE(user.registration),
info.news
FROM user,
info
WHERE user.id = info.id ";
and the registration should be showing as yyyy-mm-dd
FROM_UNIXTIME(unix_timestamp, [format]) is all you need
FROM_UNIXTIME(user.registration, '%Y-%m-%d') AS 'date_formatted'
FROM_UNIXTIME gets a number value and transforms it to a DATE object,
or if given a format string, it returns it as a string.
The older solution was to get the initial date object and format it with a second function DATE_FORMAT... but this is no longer necessary
Just use mysql's DATE function:
mysql> select DATE(mytimestamp) from foo;
You should convert timestamp to date.
select FROM_UNIXTIME(user.registration, '%Y-%m-%d %H:%i:%s') AS 'date_formatted'
FROM_UNIXTIME
If you are getting the query in your output you need to show us the code that actually echos the result. Can you post the code that calls requeteSQL?
For example, if you have used single quotes in php, it will print the variable name, not the value
echo 'foo is $foo'; // foo is $foo
This sounds exactly like your problem and I am positive this is the cause.
Also, try removing the # symbol to see if that helps by giving you more infromation.
so that
$SQL_result = #mysql_query($SQL_requete); // run the query
becomes
$SQL_result = mysql_query($SQL_requete); // run the query
This will stop any error suppression if the query is throwing an error.
I did it with the 'date' function as described in here :
(SELECT count(*) as the-counts,(date(timestamp)) as the-timestamps FROM `user_data` WHERE 1 group BY the-timestamps)
If you want to change the datatype of the column, you can simply convert first from TIMESTAMP to INT:
ALTER TABLE table_name MODIFY column_name INT;
And then INT to DATE:
ALTER TABLE table_name MODIFY column_name DATE;
But, if you didn't mean to change a column, but wanted SELECT only, then you can use date() function:
SELECT date(your_timestamp_column) FROM your_table;
I want to convert a record 1580707260
Usually, I am using online timestamp converter
Want to showcase it in the query result
Please try this
DATE_FORMAT(FROM_UNIXTIME(field name from table), '%e %b %Y')
AS 'display name for result'
Try:
SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name
It will format timestamp in milliseconds to yyyy-mm-dd string.
You can use this command FROM_UNIXTIME(unix_timestamp, [format]); but sometimes timestamp is in a long value that you have to remove 3 last values to 0.
for instance you use this command from_unixtime(e.EVENT_TIME/1000);
this way solve my problem.
I want to convert a timestamp in MySQL to a date.
I would like to format the user.registration field into the text file as a yyyy-mm-dd.
Here is my SQL:
$sql = requestSQL("SELECT user.email,
info.name,
FROM_UNIXTIME(user.registration),
info.news
FROM user, info
WHERE user.id = info.id ", "export members");
I also tried the date conversion with:
DATE_FORMAT(user.registration, '%d/%m/%Y')
DATE(user.registration)
I echo the result before to write the text file and I get :
email1;name1;DATE_FORMAT(user.registration, '%d/%m/%Y');news1
email2;name2;news2
How can I convert that field to date?
DATE_FORMAT(FROM_UNIXTIME(`user.registration`), '%e %b %Y') AS 'date_formatted'
To just get a date you can cast it
cast(user.registration as date)
and to get a specific format use date_format
date_format(registration, '%Y-%m-%d')
SQLFiddle demo
Convert timestamp to date in MYSQL
Make the table with an integer timestamp:
mysql> create table foo(id INT, mytimestamp INT(11));
Query OK, 0 rows affected (0.02 sec)
Insert some values
mysql> insert into foo values(1, 1381262848);
Query OK, 1 row affected (0.01 sec)
Take a look
mysql> select * from foo;
+------+-------------+
| id | mytimestamp |
+------+-------------+
| 1 | 1381262848 |
+------+-------------+
1 row in set (0.00 sec)
Convert the number to a timestamp:
mysql> select id, from_unixtime(mytimestamp) from foo;
+------+----------------------------+
| id | from_unixtime(mytimestamp) |
+------+----------------------------+
| 1 | 2013-10-08 16:07:28 |
+------+----------------------------+
1 row in set (0.00 sec)
Convert it into a readable format:
mysql> select id, from_unixtime(mytimestamp, '%Y %D %M %H:%i:%s') from foo;
+------+-------------------------------------------------+
| id | from_unixtime(mytimestamp, '%Y %D %M %H:%i:%s') |
+------+-------------------------------------------------+
| 1 | 2013 8th October 04:07:28 |
+------+-------------------------------------------------+
1 row in set (0.00 sec)
If the registration field is indeed of type TIMESTAMP you should be able to just do:
$sql = "SELECT user.email,
info.name,
DATE(user.registration),
info.news
FROM user,
info
WHERE user.id = info.id ";
and the registration should be showing as yyyy-mm-dd
FROM_UNIXTIME(unix_timestamp, [format]) is all you need
FROM_UNIXTIME(user.registration, '%Y-%m-%d') AS 'date_formatted'
FROM_UNIXTIME gets a number value and transforms it to a DATE object,
or if given a format string, it returns it as a string.
The older solution was to get the initial date object and format it with a second function DATE_FORMAT... but this is no longer necessary
Just use mysql's DATE function:
mysql> select DATE(mytimestamp) from foo;
You should convert timestamp to date.
select FROM_UNIXTIME(user.registration, '%Y-%m-%d %H:%i:%s') AS 'date_formatted'
FROM_UNIXTIME
If you are getting the query in your output you need to show us the code that actually echos the result. Can you post the code that calls requeteSQL?
For example, if you have used single quotes in php, it will print the variable name, not the value
echo 'foo is $foo'; // foo is $foo
This sounds exactly like your problem and I am positive this is the cause.
Also, try removing the # symbol to see if that helps by giving you more infromation.
so that
$SQL_result = #mysql_query($SQL_requete); // run the query
becomes
$SQL_result = mysql_query($SQL_requete); // run the query
This will stop any error suppression if the query is throwing an error.
I did it with the 'date' function as described in here :
(SELECT count(*) as the-counts,(date(timestamp)) as the-timestamps FROM `user_data` WHERE 1 group BY the-timestamps)
If you want to change the datatype of the column, you can simply convert first from TIMESTAMP to INT:
ALTER TABLE table_name MODIFY column_name INT;
And then INT to DATE:
ALTER TABLE table_name MODIFY column_name DATE;
But, if you didn't mean to change a column, but wanted SELECT only, then you can use date() function:
SELECT date(your_timestamp_column) FROM your_table;
I want to convert a record 1580707260
Usually, I am using online timestamp converter
Want to showcase it in the query result
Please try this
DATE_FORMAT(FROM_UNIXTIME(field name from table), '%e %b %Y')
AS 'display name for result'
Try:
SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name
It will format timestamp in milliseconds to yyyy-mm-dd string.
You can use this command FROM_UNIXTIME(unix_timestamp, [format]); but sometimes timestamp is in a long value that you have to remove 3 last values to 0.
for instance you use this command from_unixtime(e.EVENT_TIME/1000);
this way solve my problem.
Not sure really where to start with this one. Can anyone help/point me in the right direction.
I have a timestamp column in MySQL and I want to select a date range for example, all timestamps which are in Oct 2010.
Thanks.
Usually it would be this:
SELECT *
FROM yourtable
WHERE yourtimetimefield>='2010-10-01'
AND yourtimetimefield< '2010-11-01'
But because you have a unix timestamps, you'll need something like this:
SELECT *
FROM yourtable
WHERE yourtimetimefield>=unix_timestamp('2010-10-01')
AND yourtimetimefield< unix_timestamp('2010-11-01')
A compact, flexible method for timestamps without fractional seconds would be:
SELECT * FROM table_name
WHERE field_name
BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59')
If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >= and < operators as per Wouter's answer.
Here is an example of temporal fields defined with fractional second precision (maximum precision in use):
mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime;
Query OK, 1 row affected (0.01 sec)
mysql> select * from time_info;
+-----------------+----------------------------+----------------------------+---------------------+
| 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 |
+-----------------+----------------------------+----------------------------+---------------------+
1 row in set (0.00 sec)
I can see people giving lots of comments on this question. But I think, simple use of LIKE could be easier to get the data from the table.
SELECT * FROM table WHERE COLUMN LIKE '2013-05-11%'
Use LIKE and post data wild character search. Hopefully this will solve your problem.
SELECT * FROM table WHERE col >= '2010-10-01' AND col <= '2010-10-31'
This SQL query will extract the data for you. It is easy and fast.
SELECT *
FROM table_name
WHERE extract( YEAR_MONTH from timestamp)="201010";
Whenever possible, avoid applying functions to a column in the where clause:
SELECT *
FROM table_name
WHERE timestamp >= UNIX_TIMESTAMP('2010-10-01 00:00:00')
AND timestamp < UNIX_TIMESTAMP('2010-11-01 00:00:00');
Applying a function to the timestamp column (e.g., FROM_UNIXTIME(timestamp) = ...) makes indexing much harder.
If you have a mysql timestamp, something like 2013-09-29 22:27:10 you can do this
select * from table WHERE MONTH(FROM_UNIXTIME(UNIX_TIMESTAMP(time)))=9;
Convert to unix, then use the unix time functions to extract the month, in this case 9 for september.
How to find out average timestamp the field timestamp in a table gettime
Timestamp
2010-02-08 14:17:36 | 127.0.0.1 |
2010-02-08 14:17:30 | 127.0.0.1 |
2010-02-08 14:17:30 | 127.0.0.1 |
The following query gives some number how to format it and get it in seconds.
select avg(timestamp) from gettime;
the above gives some random number .How to format this
From Overview of Date and Time Types
The SUM() and AVG() aggregate
functions do not work with temporal
values. (They convert the values to
numbers, which loses the part after
the first nonnumeric character.) To
work around this problem, you can
convert to numeric units, perform the
aggregate operation, and convert back
to a temporal value.
Examples:
SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(time_col)))
FROM tbl_name;
SELECT FROM_DAYS(SUM(TO_DAYS(date_col))) FROM
tbl_name;