I have a table that contains a column (created) that stores a unix timestamp when that item has been created.
Now I want to COUNT() all items that have been created on a weekday (Monday to Friday), compared to all items that have been created on the weekened (Saturday and Sunday).
My query is:
SELECT
IF (WEEKDAY(FROM_UNIXTIME(`created`)) >= 0 AND WEEKDAY(FROM_UNIXTIME(`created`)) >= 4) THEN COUNT(*) AS `weekday`,
IF (WEEKDAY(FROM_UNIXTIME(`created`)) <= 5) THEN COUNT(*) AS `weekend`
FROM `mytable`
But the error I get is
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') THEN COUNT(*), IF (WEEKDAY(FROM_UNIXTIME(created)) <= 5) THEN COUNT(*)' at line 3
Any help is highly appreciated.
You do not appear to be using the correct syntax. http://dev.mysql.com/doc/refman/5.1/en/control-flow-functions.html#function_if
Quoted from the above url,
IF(expr1,expr2,expr3)
If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL) then IF() returns expr2; otherwise it returns expr3. IF() returns a numeric or string value, depending on the context in which it is used.".
I believe this would be the correct form for your query,
SELECT
DATE(FROM_UNIXTIME(`created`)) AS `date`,
IF (WEEKDAY(FROM_UNIXTIME(`created`)) >= 0 AND WEEKDAY(FROM_UNIXTIME(`created`)) <= 4, COUNT(*), 0), --WeekDay Count
IF (WEEKDAY(FROM_UNIXTIME(`created`)) >= 5 AND WEEKDAY(FROM_UNIXTIME(`created`)) <= 6, COUNT(*), 0) --Weekend Count
FROM mytable
I have found this link as well to the weekday function. Which leads me to believe your ranges were not correct to begin with.
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_weekday
Related
I wrote a sql query for getting number of users created in a period of time for plotting graph (grafana or chart js) , and my sql query is
SELECT
date(user.created_date) as "time",
count(distinct user.id) as Number Of User,
status as status
FROM user
WHERE
created_date >= FROM_UNIXTIME(1649635200) AND
created_date < FROM_UNIXTIME(1649894399)
GROUP BY user.status, date(user.created_date)
ORDER BY date(user.created_date)
Here in this query created date is passed dynamically from front-end,
Now i am getting the result like,
Now whenever i select the date filter from last 24 hours/12 hours some of the result is not there,
Is there is any way to modify my sql query to group by created_date with 12 hour interval
For Example, Now query result is 11/04/2022 - 5 Users(Application Created) I want query result like this 11/04/2022 00:00:00 2 - 2 users created 11/04/2022 12:00:00 - 3 users created
In grafana there is a filed $__timeFrom() and $__timeTo()
On the basis of this I rewrite my query:
SELECT
(CASE
WHEN HOUR(TIMEDIFF($__timeFrom(), $__timeTo())) <= 24
THEN user.created_date
ELSE date(user.created_date) end) AS "time",
count(distinct user.id) as Users,
FROM user
WHERE
user.created_date >= $__timeFrom() AND
user.created_date < $__timeTo() AND
GROUP BY CASE
when HOUR(TIMEDIFF($__timeFrom(), $__timeTo())) <= 24
then user.created_date
else date(created_date) end
ORDER BY CASE
when HOUR(TIMEDIFF($__timeFrom(), $__timeTo())) <= 24
then user.created_date
else date(created_date) end;
If you use this expresion in your GROUP BY, you'll get a 12-hour grouping.
DATE(created_date) + INTERVAL (HOUR(created_date) - HOUR(created_date) MOD 12) HOUR
You can, if you have the priv, declare a stored function to make this easier to read.
DELIMITER $$
DROP FUNCTION IF EXISTS TRUNC_HALFDAY$$
CREATE
FUNCTION TRUNC_HALFDAY(datestamp DATETIME)
RETURNS DATETIME DETERMINISTIC NO SQL
COMMENT 'truncate to 12 hour boundary. Returns the nearest
preceding half-day (noon, or midnight)'
RETURN DATE(datestamp) +
INTERVAL (HOUR(datestamp) -
HOUR(datestamp) MOD 12) HOUR$$
DELIMITER ;
Then you can do
SELECT
TRUNC_HALFDAY(user.created_date) as "time",
count(distinct user.id) as Number Of User,
status as status
FROM user
WHERE
created_date >= whatever AND
created_date < whatever
GROUP BY user.status, TRUNC_HALFDAY(user.created_date)
ORDER BY TRUNC_HALFDAY(user.created_date)
Even though the function appears three times in your query, because it's declared DETERMINISTIC it only gets called once per row.
More complete writeup here.
This was my SQL query:
SELECT DISTINCT Booked_From, Booked_To FROM bookings
WHERE CONVERT(DATETIME,Booked_From,101) AND CONVERT(DATETIME,Booked_To,101)
AND Hallname ='Executive Hall'
AND Booked_From >= '11/26/2021'
AND Booked_To <= '12/16/2021'
AND Bin='false'
ORDER BY str_to_date(Booked_From,'%m/%d/%Y') ASC
And this was the error generated:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Booked_From,101) AND CONVERT(DATETIME,Booked_To,101) AND Hallname ='Executive...' at line 1
Booked_From & Booked_To are VARCHARs
First of all, you should save dates always in MySQL in the form that is normal for MySQL yyyy-mm-dd. Because every conversion takes time
So in Mysql your query would be
SELECT DISTINCT Booked_From, Booked_To FROM bookings
WHERE
Hallname ='Executive Hall'
AND str_to_date(Booked_From,'%m/%d/%Y') >= str_to_date('11/26/2021','%m/%d/%Y')
AND str_to_date(Booked_To,'%m/%d/%Y') <= str_to_date('12/16/2021','%m/%d/%Y')
AND Bin='false'
ORDER BY str_to_date(Booked_From,'%m/%d/%Y') ASC;
But it would also be better to compare dates in MySQL style
SELECT DISTINCT Booked_From, Booked_To FROM bookings
WHERE
Hallname ='Executive Hall'
AND str_to_date(Booked_From,'%m/%d/%Y') >= '2021-11-26'
AND str_to_date(Booked_To,'%m/%d/%Y') <= '2021-12-16'
AND Bin='false'
ORDER BY str_to_date(Booked_From,'%m/%d/%Y') ASC
In MySQL Database I have a table ABC that consists of a column 'LastDate'.
LastDate which has datatype as DATETIME. The default value for this 'NULL'
I need to write a query for the table which would
Return '1' in these cases.
1) If DATEDIFF(CURRENT_TIME,LastDate) is >15 or if DATEDIFF(CURRENT_TIME,LastDate) is
NULL(i.e defaultVal).
return '0' if DATEDIFF(CURRENT_TIME,LastDate) is <15.
I tried to write an SQL query for this but was unable to do it. Please help me write this Query. Thanks in advance.
You can be explicit about your logic:
select t.*,
(case when DATEDIFF(CURRENT_TIME, LastDate) > 15 or
LastDate is null
then 1 else 0
end) as flag
from t;
This can be simplified to:
select t.*,
coalesce(DATEDIFF(CURRENT_TIME, LastDate) <= 15, 1) as flag
from t;
I would like to sum two columns in SQL and if the sum is greater than 0, then output it to one of the columns and if it is lesser than 0, then output to another column.
My code looks like this:
SELECT IF(SUM(`processed_quantity_long`,-1*`processed_quantity_short`) > 0,SUM(`processed_quantity_long`,-1*`processed_quantity_short`) AS `Position Long`,SUM(`processed_quantity_long`,-1*`processed_quantity_short`) AS `Position Short`)
From table A
GROUPBY date
It is returning me this error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '-1*processed_quantity_short)>0,SUM(processed_quantity_long,-1*`processed_qua' at line 5
Not sure how to resolve this error.
SUM does not take two arguments. Just subtract the two numbers before calculating the sum:
SELECT
CASE WHEN SUM(processed_quantity_long - processed_quantity_short) >= 0 THEN SUM(processed_quantity_long - processed_quantity_short) END AS `Position Long`,
CASE WHEN SUM(processed_quantity_long - processed_quantity_short) < 0 THEN SUM(processed_quantity_long - processed_quantity_short) END AS `Position Short`
FROM tablea
GROUP BY date
you did wrong on inside if
SELECT IF(
SUM(processed_quantity_long-processed_quantity_short) > 0,
SUM(`processed_quantity_long`-`processed_quantity_short`) ,
SUM(`processed_quantity_long`-`processed_quantity_short`) AS `Position Short`
) From tableA GROUP BY date
general if statement is like below
SELECT IF(500<1000, "YES", "NO")
Or use case when
case when SUM(`processed_quantity_long`-`processed_quantity_short`) > 0
then SUM(`processed_quantity_long`-`processed_quantity_short`)
else SUM(`processed_quantity_long`-`processed_quantity_short`) as position
from tableA GROUP BY date
Perhaps the simplest way to write the code is:
SELECT GREATEST(SUM(processed_quantity_long - processed_quantity_short), 0) AS Position_Long,
LEAST(SUM(processed_quantity_long - processed_quantity_short), 0) AS Position_Short
FROM tablea
GROUP BY date
Trying to get this query to work. I'm having issues with brackets I think.
SELECT (fielda - fieldb - (
IF ((cola <= 5),
1,
IF ((cola >= 6 AND cola <= 12),
2,
IF ((cola >= 13 AND cola <= 20),
3,
IF ((cola >= 21 AND cola <= 28), 4)
)
)
) ))
AS result FROM the table r WHERE r.fieldx = 3148 AND cola <= 18 ORDER BY result LIMIT 1
Mysql returns:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')))) ) AS result FROM
The last IF does not have an else argument. While one might expect MySQL to understand this anyhow, it doesn't appear to be valid syntax according to http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_if
If I had to guess (and going by the information you've provided) I would say the last IF() is missing an else condition which is making the math function fail.
IF ((cola >= 21 AND cola <= 28), 4, ???)
Populate the question marks with an "all else fails"/"default" value and you should be safe. However, I believe mysql (assuming it's a non-nullable field) will use the default value for the type/column if you specify NULL as the else condition (but I may be wrong).