I am trying to add hours to current time like
-- NOT A VALID STATEMENT
-- SELECT GetDate(DATEADD (Day, 5, GETDATE()))
How can I get hours ahead time in SQL Server?
DATEADD (datepart , number , date )
declare #num_hours int;
set #num_hours = 5;
select dateadd(HOUR, #num_hours, getdate()) as time_added,
getdate() as curr_date
Select JoiningDate ,Dateadd (day , 30 , JoiningDate)
from Emp
Select JoiningDate ,DateAdd (month , 10 , JoiningDate)
from Emp
Select JoiningDate ,DateAdd (year , 10 , JoiningDate )
from Emp
Select DateAdd(Hour, 10 , JoiningDate )
from emp
Select dateadd (hour , 10 , getdate()), getdate()
Select dateadd (hour , 10 , joiningDate)
from Emp
Select DateAdd (Second , 120 , JoiningDate ) , JoiningDate
From EMP
The DATEADD() function adds or subtracts a specified time interval from a date.
DATEADD(datepart,number,date)
datepart(interval) can be hour, second, day, year, quarter, week etc;
number (increment int);
date(expression smalldatetime)
For example if you want to add 30 days to current date you can use something like this
select dateadd(dd, 30, getdate())
To Substract 30 days from current date
select dateadd(dd, -30, getdate())
declare #hours int = 5;
select dateadd(hour,#hours,getdate())
SELECT GETDATE() + (hours / 24.00000000000000000)
Adding to GETDATE() defaults to additional days, but it will also convert down to hours/seconds/milliseconds using decimal.
If you are using mySql or similar SQL engines then you can use the DATEADD method to add hour, date, month, year to a date.
select dateadd(hour, 5, now());
If you are using postgreSQL you can use the interval option to add values to the date.
select now() + interval '1 hour';
Related
How do I select date range from this query?
E.g : From Month('2017-05-22') And Year(date1) = Year('2017-05-22')
to Month('2018-05-22') And Year(date1) = Year('2018-05-22')
My current query :
SELECT
date1
FROM
data
WHERE
Month(date1) = Month('2018-05-22') And Year(date1) = Year('2018-05-22')
I'd convert those literals to dates using str_to_date:
SELECT MONTH(date1)
FROM data
WHERE date1 BETWEEN STR_TO_DATE('2017-05-22', '%Y-%m-%d') AND STR_TO_DATE('2018-05-23', '%Y-%m-%d')
Note that between is inclusive on the first argument and exclusive on the second, so I bumped the day to the 23rd.
BETWEEN condition to retrieve values within a date range.
For example:
SELECT *
FROM order_details
WHERE order_date BETWEEN CAST('2014-02-01' AS DATE) AND CAST('2014-02-28' AS DATE);
This MySQL BETWEEN condition example would return all records from the order_details table where the order_date is between Feb 1, 2014 and Feb 28, 2014 (inclusive). It would be equivalent to the following SELECT statement:
SELECT *
FROM order_details
WHERE order_date >= CAST('2014-02-01' AS DATE)
AND order_date <= CAST('2014-02-28' AS DATE);
SELECT TO_CHAR(systemts, 'yyyy-mm') as yyyymm,
max(notenum) - min(notenum) + 1 as notenum_range
FROM your_table_name
WHERE systemts >= to_date('2018-01-01', 'yyyy-mm-dd') AND
systemts < to_date('2018-07-17', 'yyyy-mm-dd')
GROUP BY TO_CHAR(systemts, 'yyyy-mm');
DECLARE #monthfrom int=null,
#yearfrom int=null,
#monthto int=null,
#yearto int=null
/**Region For Create Date on Behalf of Month & Year**/
DECLARE #FromDate DATE=NULL
DECLARE #ToDate DATE=NULL
SET #FromDate=DateAdd(day,0, DateAdd(month, #monthfrom - 1,DateAdd(Year, #yearfrom-1900, 0)))
SET #ToDate=DateAdd(day,-1, DateAdd(month, #monthto - 0,DateAdd(Year, #yearto-1900, 0)))
/**Region For Create Date on Behalf of Month & Year**/
SELECT DISTINCT month ,Year FROM tbl_Att
WHERE (DATEADD(yy, year - 1900, DATEADD(m, Month - 1, 1 - 1)) BETWEEN CONVERT(DATETIME, #FromDate, 102) AND
CONVERT(DATETIME, #ToDate, 102))
Is it possible in MySQL to easily to get the number of days between two dates, group by months and then disperse those days between the months, so that when I group by month, I get to see how many days inbetween two those two dates fall into each month.
Example: creation 05.05.2014 to expiration 06.06.2014 returns 32 days. I want to display this as:
May: 26 days
June: 5 days
So far I've got:
SELECT MONTHNAME(date) as month_name,
SUM(DATEDIFF(expiration, date)) AS num_days
FROM reservations
GROUP BY month_name
But it doesn't disperse the days corretly by month, just drop them all into the group-by -start-date-month, obviously. Any ideas would be highly appriciated.
I would build a comprehensive date temp table (or CTE) first.
From there you can select what you'd like, and group it however suits your needs.
IF OBJECT_ID('TEMPDB..#Dates') IS NOT NULL DROP TABLE #Dates
DECLARE #StartDate DATETIME, #EndDate DATETIME
SET #StartDate = '05/05/2014'
SET #EndDate = '06/06/2014'
;WITH Dates AS
(
SELECT CAST(CONVERT(VARCHAR(8), #StartDate,112) AS INT) AS DateId
, CAST(#StartDate AS DATE) AS Date
, CAST(#StartDate AS DATETIME) AS DateTime
, DATEPART(QUARTER, #StartDate) AS QuarterId
, 'Q' + CAST(DATEPART(QUARTER,#StartDate) AS CHAR(1)) AS Quarter
, DATEPART(MONTH, #StartDate) AS MonthId
, DATENAME(MONTH, #StartDate) AS Month
, DATEPART(DAY, #StartDate) AS Day
, DATEPART(YEAR, #StartDate) AS Year
, DATENAME(DW,#StartDate) AS DayOfWeek
, DATEPART(DAYOFYEAR, #StartDate) AS DayOfYear
UNION ALL
SELECT CAST(CONVERT(VARCHAR(8),DATEADD(DAY, 1, D.DateTime), 112) AS INT) ASDateId
, CAST(DATEADD(DAY, 1, D.DateTime) AS DATE) AS Date
, CAST(DATEADD(DAY, 1, D.DateTime) AS DATETIME) AS DateTime
, DATEPART(QUARTER,DATEADD(DAY,1,D.DateTime)) AS QuarterId
,'Q'+CAST(DATEPART(QUARTER,DATEADD(DAY, 1, D.DateTime)) AS CHAR(1)) AS Quarter
, DATEPART(MONTH,DATEADD(DAY, 1, D.DateTime)) AS MonthId
, DATENAME(MONTH,DATEADD(DAY, 1,D.DateTime)) AS Month
, DATEPART(DAY,DATEADD(DAY, 1, D.DateTime)) AS Day
, DATEPART(YEAR,DATEADD(DAY, 1, D.DateTime)) AS Year
, DATENAME(DW,DATEADD(DAY,1, D.DateTime)) AS DayOfWeek
, DATEPART(DAYOFYEAR,DATEADD(DAY,1, D.DateTime)) AS DayOfYear
FROM Dates AS D
WHERE D.DateTime < #EndDate
)
SELECT DateId AS DateId
, Date AS Date
, DateTime AS DateTime
, QuarterId AS QuarterId
, Quarter AS Quarter
, MonthId AS MonthId
, Month AS Month
, Day AS Day
, Year AS Year
, DayOfWeek AS DayOfWeek
, DayOfYear AS DayOfYear
, ROW_NUMBER() OVER(ORDER BY DateId)-1 AS DayCount
INTO #Dates
FROM Dates AS D
ORDER BY D.DateId
OPTION (MAXRECURSION 32767)
-- SELECT * FROM #Dates
SELECT COUNT(Day) AS CountOfDays, Month
FROM #Dates
GROUP BY Month
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'
How to select week data (more precisely, last 7 days data) from the current date in the fastest way as I have millions or rows in the table. I have a time stamp of created_date in sql table.
I have tried this
SELECT Created_Date
FROM Table_Name
WHERE Created_Date >= DATEADD(day,-7, GETDATE())
I have two question:
Is this query is correct?
Is this is the fastest way to get the last seven day data from a table having millions of rows ?
Yes, the syntax is accurate and it should be fine.
Here is the SQL Fiddle Demo I created for your particular case
create table sample2
(
id int primary key,
created_date date,
data varchar(10)
)
insert into sample2 values (1,'2012-01-01','testing');
And here is how to select the data
SELECT Created_Date
FROM sample2
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())
to select records for the last 7 days
SELECT * FROM [TableName]
WHERE Created_Date >= DATEADD(day, -7, GETDATE())
to select records for the current week
SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT * FROM [TableName]
WHERE CreatedDate >= DATEADD(day, 1 - DATEPART(WEEKDAY, GETDATE()), CONVERT(DATE, GETDATE()))
AND CreatedDate < DATEADD(day, 8 - DATEPART(WEEKDAY, GETDATE()), CONVERT(DATE, GETDATE()))
if you want to select records for last week instead of the last 7 days
SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT * FROM [TableName]
WHERE CreatedDate >= DATEADD(day, -(DATEPART(WEEKDAY, GETDATE()) + 6), CONVERT(DATE, GETDATE()))
AND CreatedDate < DATEADD(day, 1 - DATEPART(WEEKDAY, GETDATE()), CONVERT(DATE, GETDATE()))
The query is correct
2A. As far as last seven days have much less rows than whole table an index can help
2B. If you are interested only in Created_Date you can try using some group by and count, it should help with the result set size
Given:
Start Year
Start Month & Start Day
End Month & End Day
What SQL statement results in TRUE if a date lands between the Start and End days? The problem is in finding the end year so as to get a start_date and an end_date.
Maybe convert the dates to UNIX timestamps? Then it would be simple less-than or greater-than integer arithmetic.
Do you really need true/false values, or can you just SELECT? Assuming $date contains the date you're looking for in 'yyyy-mm-dd' format:
SELECT * FROM mytable WHERE $date > start_date AND date < end_date;
Having the year in a separate field also works, but looks uglier and probably kills performance:
SELECT * FROM mytable WHERE $date > CONCAT(year, '-', start_date) AND
$date < CONCAT(year, '-', end_date);
And with handling for the end < start case:
SELECT * FROM mytable WHERE $date > CONCAT(year, '-', start_date) AND $date <
IF(start_date < end_date,
CONCAT(year, '-', end_date),
DATE_ADD(CONCAT(year, '-', end_date), INTERVAL 1 YEAR));
One way to calculate the end year (so as to derive the end_date):
end_year = start_year +
greatest( -1 *
sign(
datediff(
date(
concat_ws('-', year, end_month, end_day )
),
date(
concat_ws('-', year, start_month, start_day )
)
)
), 0
)