case when query in mysql - mysql

I want to execute below query,
when date diff is greater than 1 , how to add that in when clause as diffdate is not available there.
select
CASE (
SELECT DATEDIFF('2014-11-30','2015-11-29') AS DiffDate
)
WHEN 1 THEN "1 Day"
WHEN 7 THEN "Week"
WHEN ??? THEN "Yearly"
END;

Use an else
select CASE DATEDIFF('2014-11-30','2015-11-29')
WHEN 1 THEN '1 Day'
WHEN 7 THEN '7 Days'
ELSE 'Yearly'
END;

Related

How to display the time result with 24 hour calculation

For example, server time is 15:00:00. I run the following query but it gives me wrong result. Here my query
SELECT
CASE
WHEN TIME(NOW()) BETWEEN '08:00:01' AND '10:00:00'
THEN 1
WHEN TIME(NOW()) BETWEEN '14:00:01' AND '08:00:00'
THEN 2
ELSE 0
END AS IdShift
What's wrong with my query ? from that case my expected result is 2. but it give me 0
In a BETWEEN clause you have to specify the lower value first, then the higher value.
So you have to change BETWEEN '14:00:01' AND '08:00:00' to BETWEEN '08:00:00' AND '14:00:01'.
When you want to span from 14:00 to the next day 08:00 you have to include the date.
You could do it like this:
SELECT
CASE
WHEN NOW() BETWEEN CONCAT(CURDATE(), ' 08:00:01') AND CONCAT(CURDATE(), ' 10:00:00')
THEN 1
WHEN NOW() BETWEEN CONCAT(CURDATE(), ' 14:00:01') AND CONCAT(CURDATE() + INTERVAL 1 DAY, ' 08:00:00')
THEN 2
ELSE 0
END AS IdShift
As mentioned in another answer, for between the lower bound is always first. I'm not a fan of between, but you need to split your conditions:
SELECT (CASE WHEN TIME(NOW()) BETWEEN '08:00:01' AND '10:00:00'
THEN 1
WHEN TIME(NOW()) BETWEEN '14:00:01' AND '23:59:59'
THEN 2
WHEN TIME(NOW()) BETWEEN '00:00:00' AND '08:00:00'
THEN 2
ELSE 0
END) AS IdShift
Or, phrase this with or:
SELECT (CASE WHEN TIME(NOW()) > '08:00:00' AND TIME(NOW()) <= '10:00:00'
THEN 1
WHEN TIME(NOW()) > '14:00:00' OR TIME(NOW()) < '08:00:00'
THEN 2
ELSE 0
END) AS IdShift
I would be inclined to shift the logic by a minute or two and use hours:
(case when hour(now()) >= 8 and hour(now()) < 10
then 1
when hour(now()) >= 14 or hour(now()) < 8
then 2
end)

In mysql How to find number of sundays in a month

In mysql how to find number of sundays in month by usnig month in where clause
Ex:
month(log_date)=month(now());
month(log_date) = 12;
output: 5 sundays
Possible way to do it which avoids using any tables. This finds the number of days in the month, and depending on that and what day of the week the last day is then it just returns a value
SELECT CASE DAYOFMONTH(LAST_DAY(NOW()))
WHEN 31 THEN
CASE DAYOFWEEK(LAST_DAY(NOW()))
WHEN 1 THEN 5
WHEN 2 THEN 5
WHEN 3 THEN 5
ELSE 4
END
WHEN 30 THEN
CASE DAYOFWEEK(LAST_DAY(NOW()))
WHEN 1 THEN 5
WHEN 2 THEN 5
ELSE 4
END
WHEN 29 THEN
CASE DAYOFWEEK(LAST_DAY(NOW()))
WHEN 1 THEN 5
ELSE 4
END
ELSE 4
END
SQL query for get total sunday in given month from DB
USE BETWEEN :- BETWEEN operator selects values within a given range.
Note :- DAYOFWEEK actually returns 1 for Sunday
SELECT count(*) AS total_sunday FROM `table` WHERE DAYOFWEEK(`date`) = 1 BETWEEN '2017-11-01' AND '2017-11-30';
In mysql just copy and paste the query given below. It will give you number of Sundays in current month.
WITH RECURSIVE offdays as(
SELECT
LAST_DAY(CURDATE()-INTERVAL 1 MONTH) + INTERVAL 1 DAY AS `Date`,
DAYNAME(LAST_DAY(CURDATE()-INTERVAL 1 MONTH) + INTERVAL 1 DAY) AS `DayName`
UNION ALL
SELECT `Date` + INTERVAL 1 DAY, DAYNAME(`Date` + INTERVAL 1 DAY)
FROM offdays WHERE `DATE` < LAST_DAY(CURDATE())
) SELECT count(*) FROM offdays where DAYNAME(DATE) = 'Sunday';
you will get number of sundays in current month. Just replace the CURDATE() with any date. The query will give you the number of Sundays of the month of the date supplied.
Try this function, you use like
count_days_in_month($date_month,$day_idx);
$day_idx is 1 - 7 where Sunday is 1, Saturday is 7
eg.
select count_days_in_month('2020-02-01',1);
delimiter //
create or replace function count_days_in_month(input_date DATE,dayindex INT)
returns INT
DETERMINISTIC
BEGIN
declare start_day_idx INT default (select dayofweek( date_sub(input_date,INTERVAL (DAYOFMONTH(input_date)-1) DAY )) from dual);
declare days_in_month INT default (SELECT dayofmonth(LAST_DAY(input_date)));
declare days_over_28 INT default (days_in_month-28);
if days_in_month > 28 then
if (days_over_28 > (dayindex-start_day_idx)) and ((dayindex-start_day_idx) >= 0) then
return 5;
else
return 4;
end if;
else
return 4;
end if;
END//
Eg to test the count of all days in a month:
select
count_days_in_month('2020-02-01',1) 'Sun',
count_days_in_month('2020-02-01',2) 'Mon',
count_days_in_month('2020-02-01',3) 'Tue',
count_days_in_month('2020-02-01',4) 'Wed',
count_days_in_month('2020-02-01',5) 'Thur',
count_days_in_month('2020-02-01',6) 'Fri',
count_days_in_month('2020-02-01',7) 'Sat'
from
dual;//

(MYSQL] Use an "CASE ... WHEN" alias in a date_add function

Can I use an alias create with the "CASE ... WHEN" (delayDate), in another function, like date_add() :
doctrine way :
->addSelect("CASE c.time
WHEN '24' then 1
WHEN '48' then 2
WHEN '72' then 3
WHEN '96' then 4
ELSE 0
END
as delayDate ,
date_add(CURRENT_DATE(), delayDate, 'DAY') as firstDateDelivery")
This because I can't use 'HOUR' in doctrine with the date_add() function.
I think, in "pure" mysql, it's not working anymore...
Can you help me please ?
F.
Remove single quote from DAY, and check this DATE_ADD() usage func_date_add.
->addSelect("CASE c.time
WHEN '24' then 1
WHEN '48' then 2
WHEN '72' then 3
WHEN '96' then 4
ELSE 0
END
as delayDate ,
CASE c.time
WHEN '24' then date_add(CURRENT_DATE(), INTERVAL 1 DAY)
WHEN '48' then date_add(CURRENT_DATE(), INTERVAL 2 DAY)
WHEN '72' then date_add(CURRENT_DATE(), INTERVAL 3 DAY)
WHEN '96' then date_add(CURRENT_DATE(), INTERVAL 4 DAY)
ELSE CURRENT_DATE()
END
as firstDateDelivery")

Last date in quarter MySQL

I have a table with some dates. I need a query which will return the max (last) date from this table and last date of quarter this max date belongs to.
So for data i table
ID| EDATE
--+----------
1|2014-03-06
2|2014-10-12
this query should return 2014-10-12 and 2014-12-31.
As I understand you want the last day of the quarter, so 31 March, 30 June, 30 Sept, 31 Dec? So you can use the answer from Gordon Linoff and adjust it to do that.
You only need a case statement on month(date) and concat that with the year.
http://dev.mysql.com/doc/refman/5.1/de/control-flow-functions.html
str_to_date(
concat(
year(edate),
(case
when month(edate) in (1, 2, 3) then '-03-31'
when month(edate) in (4, 5, 6) then '-06-30'
when month(edate) in (7, 8, 9) then '-09-30'
else '-12-31'
end)
),
'%Y-%m-%d'
)
Getting the day of the last quarter for the date is a bit yucky, but possible. Here is a sort of brute force solution:
select edate,
str_to_date(concat(year(edate), '-', 1 + floor((month(edate) - 1)/ 3)) * 3, '-',
(case when month(edate) in (1, 2, 3, 10, 11, 12) then 31 else 30 end)),
'%Y-%m-%d'
)
from table t
order by edate desc
limit 1;
Here is a SQL Fiddle that demonstrates it.
You can use LAST_DAY to select the last day of a specific month depending on where your quarters end you may have to change the 3,6,9,12 to different months.
select t1.max_date,
(
case
when month(max_date) <= 3
then last_day(concat(year(max_date),'-3-1'))
when month(max_date) <= 6
then last_day(concat(year(max_date),'-6-1'))
when month(max_date) <= 9
then last_day(concat(year(max_date),'-9-1'))
else last_day(concat(year(max_date),'-12-1'))
end
) last_quarter_day
from (
select max(EDATE) max_date from myTable
) t1
I found the simplest answer:
SELECT MAKEDATE(YEAR(edate),1)
+ INTERVAL QUARTER(edate) QUARTER
- INTERVAL 1 DAY
This query takes the first day of year, adds quarters to it and subtracts 1 day to get the last day in wanted quarter. So the required query should look like:
SELECT MAX(edate),
MAKEDATE(YEAR(MAX(edate)),1)
+ INTERVAL QUARTER(MAX(edate)) QUARTER
- INTERVAL 1 DAY
FROM table

How to calculate number of Sundays between two dates using mysql

I need to find number of Sundays between two dates using mysql. I know how to do it using PHP But i need it to be calculated using mysql.
SET #START_DATE = '2014-01-22';
SET #END_DATE = '2014-06-29';
SELECT
ROUND((
(unix_timestamp(#END_DATE) - unix_timestamp(#START_DATE) ) /(24*60*60)
-7+WEEKDAY(#START_DATE)-WEEKDAY(#END_DATE)
)/7)
+ if(WEEKDAY(#START_DATE) <= 6, 1, 0)
+ if(WEEKDAY(#END_DATE) >= 6, 1, 0) as Sundays;
Solution consist of 2 parts:
counts number of full weeks (ROUND part), obviously you'll have 7 Sundays in 7 weeks.
count days that are included into the not full week parts (first or last)
If you'll need to use it more than once you can wrap it into the function:
DROP function IF EXISTS `count_weekdays`;
DELIMITER $$
CREATE FUNCTION `count_weekdays` (startDate date, endDate date, wd int)
RETURNS INTEGER
BEGIN
RETURN ROUND((
(unix_timestamp(endDate) - unix_timestamp(startDate) ) /(24*60*60)
-7+WEEKDAY(startDate)-WEEKDAY(endDate)
)/7)
+ if(WEEKDAY(startDate) <= wd, 1, 0)
+ if(WEEKDAY(endDate) >= wd, 1, 0);
END$$
DELIMITER ;
Then you will be able to use it like this:
SET #START_DATE = '2018-07-03';
SET #END_DATE = '2018-07-28';
select
count_weekdays(#START_DATE, #END_DATE, 6) as Sundays,
count_weekdays(#START_DATE, #END_DATE, 5)
+ count_weekdays(#START_DATE, #END_DATE, 6) as weekends;
Where 6 ~ number of weekday stands for Sunday, 5 ~ Saturday.
http://sqlfiddle.com/#!2/d41d8/50695
Maybe there will be no code on this link someday so I posted it here.
the upper link will show the number of the day and with date of the sundays. if you want to find any other day change the 1 at last to 2 for monday
select DATE_ADD('2012-12-15', INTERVAL ROW DAY) as Date,
row+1 as DayOfMonth from (
SELECT #row := #row + 1 as row FROM
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6) t1,
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6) t2,
(SELECT #row:=-1) t3 limit 31
) b
where
DATE_ADD('2012-12-01', INTERVAL ROW DAY)
between '2012-12-01' and '2012-12-31'
and
DAYOFWEEK(DATE_ADD('2012-12-01', INTERVAL ROW DAY))=1
Does this work...
SELECT FLOOR(
(DATEDIFF(
'#enddate'
,'#startdate' + INTERVAL
LENGTH(SUBSTRING_INDEX('654321',WEEKDAY('#startdate'),1))
DAY) + 1)/7) + 1 x;
SELECT a.StartDate, a.EndDate,
(DAY(EndDate - StartDate) / 7)
+ iif(DAY(EndDate - StartDate)%7 + DATEPART(DW, StartDate) > 8 , 1, 0)
Sundays FROM
(SELECT GETDATE() StartDate, DATEADD(DAY, 11, GETDATE()) EndDate) a
This is useful for multiple start and end dates in a table.
no need of variables and loops!
How it works: determines the number of full weeks between start and end date,
determines the days less than a week and add with the start day index(1,2,3,4,5,6,7) if that value Greater than count 8(means which is Sunday !)
For Sunday week day index is 1, day 8 is nothing but index 1.
SELECT COUNT(*) FROM table_name
WHERE column BETWEEN 'start_date' AND 'end_date'
AND WEEKDAY(date) = 6;
Refer this, mysql have a function dayofweek, you can easily calculate starting week day and after that divide the number of days with 7:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofweek
OR
SELECT COUNT(*) FROM table_name
WHERE date_column_of_table_name BETWEEN '2013-01-11' AND '2013-03-01'
AND WEEKDAY(date_column_of_table_name) = 6
Try this
select count(DAYNAME(your_date_field)='Sunday') as sunday from tbl_name where your_date_field between 'date1' AND 'date2'