date_trunc PostgreSQL function equal for mySQL - mysql

Im trying to retrieve data to make statistics, im using mySQL and i cant get the following function to work - the postgreSQL is working.
I want to retrieve the request for the last month and count the amount of new requests for each day.
postgreSQL
SELECT count(*), date_trunc('day', created_at) as date FROM requests
WHERE(created_at > '2014-08-13 00:00:00') GROUP BY 2 ORDER BY 2 ASC;
*mySQL - my code *
SELECT count(EXTRACT(DAY FROM created_at)), EXTRACT(DAY FROM created_at) as date
FROM `requests`
WHERE EXTRACT(DAY FROM NOW() - INTERVAL 1 MONTH)
GROUP BY date
Final code
SELECT count( * ) , date( created_at ) AS date
FROM `requests`
WHERE DATE( created_at ) > DATE( DATE_SUB( NOW( ) , INTERVAL 1 MONTH ) )
GROUP BY date

The equivalent for your case is date():
select date(created_at), count(*)
from requests
. . .
This isn't a general replacement, but it works to remove the time portion of a date.
EDIT:
Perhaps the better solution for these two databases is:
select cast(created_at as date)
This is ANSI standard and works in both these databases (as well as SQL Server). I personally don't use this in general, lest I accidentally use it in Oracle, causing difficult to find errors. (dates in Oracle have a time component, alas.)

Related

MYSQL max() and group by error:only_full_group_by

I have question about a MySQL query that is logging error's since updating the MySQL-5.7.
The error is the "only_full_group_by" which is will spoken off on stackoverflow.
In many answers it's stated not to disable this option but improve your sql query.
The query that I'm using is returning the minimum and maximum values of a counter per hour.
SELECT MAX( counter ) AS max,
MIN( counter ) AS min,
DATE_FORMAT(date_time, '%H:%i') AS dt
FROM table1
WHERE date_time >= NOW() - INTERVAL 1 DAY
GROUP BY YEAR(date_time), MONTH(date_time), DAY(date_time), HOUR(date_time)
as I understand from the error message I'm missing one of the items from the SELECT cause in the GROUP BY cause. But however I restort/remove/add items I'm not getting the result I got before the upgrade to MySQL-5.7.
I tried to subquery the main query to improve the SQL query. But somehow I can't recreate the results.
What is it I'm missing?
MySQL isn't able to determine the functional dependence ... between the expressions in the GROUP BY clause, and the expressions in the SELECT list.
The non-aggregate expression in the SELECT list (DATE_FORMAT(date_time, '%H:%i') includes a minutes component. The GROUP BY clause is going to collapse the rows into groups by just hour. So the value of the minutes is indeterminate... we know it's going to come from some row in the group, but there's no guarantee which one.
(The question reference to ONLY_FULL_GROUP_BY seems to indicate that we've got some understanding of indeterminate values...)
The easiest (fewest) changes fix would be to wrap that expression in a MIN or MAX function.
SELECT MAX(t.counter) AS `max`
, MIN(t.counter) AS `min`
, MIN(DATE_FORMAT(t.date_time,'%H:%i')) AS `dt`
FROM table1 t
WHERE t.date_time >= NOW() - INTERVAL 1 DAY
GROUP
BY YEAR(t.date_time)
, MONTH(t.date_time)
, DAY(t.date_time)
, HOUR(t.date_time)
ORDER
BY YEAR(t.date_time)
, MONTH(t.date_time)
, DAY(t.date_time)
, HOUR(t.date_time)
If we want rows returned in a particular order, we should include an ORDER BY clause, and not rely on MySQL-specific extension or behavior of GROUP BY (which may disappear in future releases.)
It's a bit odd to be doing a GROUP BY year, month, day and not including those values in the SELECT list. (It's not invalid to do that, just kind of strange. The conditions in the WHERE clause are guaranteeing that we don't have more than 24 hours span for date_time.
My preference would to do the GROUP BY on the same expression as the non-aggregate in the SELECT list. If I ever needed more than 24 hours, I'd include the date component:
SELECT MAX(t.counter) AS `max`
, MIN(t.counter) AS `min`
, DATE_FORMAT(t.date_time,'%Y-%m-%d %H:00') + INTERVAL 0 DAY AS `dt`
FROM table1 t
WHERE t.date_time >= NOW() - INTERVAL 1 DAY
GROUP
BY DATE_FORMAT(t.date_time,'%Y-%m-%d %H:00') + INTERVAL 0 DAY
ORDER
BY DATE_FORMAT(t.date_time,'%Y-%m-%d %H:00') + INTERVAL 0 DAY
--or--
if we always know it's just one day's worth of date_time, and we only want to return the hour, then we can group by just the hour. The same expression as in the SELECT list.
SELECT MAX(t.counter) AS `max`
, MIN(t.counter) AS `min`
, DATE_FORMAT(t.date_time,'%H:00') AS `dt`
FROM table1 t
WHERE t.date_time >= NOW() - INTERVAL 1 DAY
GROUP
BY DATE_FORMAT(t.date_time,'%H:00')
, DATE_FORMAT(t.date_time,'%Y-%m-%d %H')
ORDER
BY DATE_FORMAT(t.date_time,'%Y-%m-%d %H')
SELECT MAX( counter ) AS max,
MIN( counter ) AS min,
YEAR(date_time) AS g_year,
MONTH(date_time)AS g_month,
DAY(date_time) AS g_day,
HOUR(date_time) AS g_hour
FROM table1
WHERE date_time >= NOW() - INTERVAL 1 DAY
GROUP BY g_year, g_month, g_day, g_hour
Or you can get rid of redundant data if you always do it for 1 day:
SELECT MAX( counter ) AS max,
MIN( counter ) AS min,
DAY(date_time) AS g_day,
HOUR(date_time) AS g_hour
FROM table1
WHERE date_time >= NOW() - INTERVAL 1 DAY
GROUP BY g_day, g_hour

Sql query too slow - looking for alternative way to write it

I have this mysql query that does what it needs to but it takes a really long time to load the content where as my other queries run perfectly fine and quick. Is there a better way to do it? I just want it to load faster. Here is my query:
SELECT
DISTINCT( # Without this I get too many results
CONCAT_WS(' ',
MONTHNAME(a.DateTimeViewed),
YEAR(a.DateTimeViewed)
)
) AS ViewedDate, # Displays as "January 2017" (example)
(
SELECT COUNT(b.ViewID)
FROM views b
WHERE
MONTH(b.DateTimeViewed) = MONTH(a.DateTimeViewed) AND
YEAR(b.DateTimeViewed) = YEAR(a.DateTimeViewed)
) as TotalViews
FROM views a
WHERE a.DateTimeViewed >= date_sub(now(), interval 6 month)
ORDER BY YEAR(a.DateTimeViewed) ASC, MONTH(a.DateTimeViewed) ASC
You are working too hard.
SELECT CONCAT_WS(' ', MONTHNAME(a.DateTimeViewed), YEAR(a.DateTimeViewed)
) AS ViewedDate,
COUNT(*) as TotalViews
FROM views a
WHERE a.DateTimeViewed >= date_sub(now(), interval 6 month)
ORDER BY YEAR(a.DateTimeViewed) ASC, MONTH(a.DateTimeViewed) ASC
Since you are backing up 6 months from this instant, you are getting the count for only part of the first month. Perhaps you want to change one line:
WHERE a.DateTimeViewed >= CONCAT(LEFT(CURDATE() - INTERVAL 6 MONTH, 7), '-01')
COUNT(*) is the usual way to count rows. COUNT(x) does the same, but adds on the effort to filter out rows with x IS NULL.

Count on curdate() in mysql

I have a user_entry table which contains a date field. data type is datetime.
data base is mysql.
I want a count of current date and current month and all data of current date.
How can I get this?
I tried below query but it's not working.
select * from table
where DATE(date) = CURDATE()
SELECT date FROM `test` WHERE date = CURDATE()
or
SELECT date FROM `test` WHERE date = DATE('2016-04-04')
it's work.
if you want the number of matches:
SELECT COUNT(date) from test WHERE date = CURDATE()
What is the data type of field 'date'?
To obtain the DAY/MONTH you can use the corresponding functions
SELECT MONTH(date), DAY(date) from test
Moreover, you can use groups to create a complete report
SELECT COUNT(date), date from test GROUP BY DAY(date), MONTH(date)
i used below query and it works for me.
SELECT *
FROM `user_entry`
WHERE DATE( DATE ) = DATE( NOW( ) )

how to filter a select statement in mysql for a particular time period without using now()

I have tried to filter records but with the use of now function as given below
select * from table where date>= DATE_SUB( NOW( ) ,INTERVAL 90 DAY )
What I need is a select statement that can filter its records for a week or month from the current date but without using NOW() function
if you are using java you could make use of the following code
String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
or you could use curdate() of mysql
Since I found it hard to understand the question I provide the following possibilities:
Try for all dates in a week from now:
SELECT * FROM table
WHERE date BETWEEN CURDATE() AND DATE_ADD(CURDATE() ,INTERVAL 1 WEEK)
and for all dates in a month from now:
SELECT * FROM table
WHERE date BETWEEN CURDATE() AND DATE_ADD(CURDATE() ,INTERVAL 1 MONTH)
If you are looking for all dates of the current month use
SELECT * FROM table
WHERE MONTH(date)=MONTH(CURDATE()) AND YEAR(date)=YEAR(CURDATE())
or for all dates of the current week use
SELECT * FROM table
WHERE WEEK(date)=WEEK(CURDATE()) AND YEAR(date)=YEAR(CURDATE())

Fetch data from last day, week, month and year in Mysql

I read many topics to fetch data that posted in different periods, but as the Time in my mysql table is in STRING format I couldn't make it happen.
SELECT s.user_id, count(*) AS wins, u.username, u.avatar,u.avatar_uploaded
FROM on_scores AS s
LEFT JOIN on_users AS u ON (u.userid = s.user_id)
WHERE s.is_high = '1' AND DATE(s.date_score) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
GROUP BY s.user_id
ORDER BY wins DESC
LIMIT 10
I tried the STR_TO_DATE method but still no output.
Use the from_unixtime function to get the time into a date-like format.
More info here.
Information on formatting the resultant date - here.
Example:
select date_sub( from_unixtime( s.datescore ), INTERVAL 1 MONTH ) as monthfromdatevalue;
select datediff( from_unixtime( s.datescore, curdate()) as howlongago_fromtoday;