What is this `DateAdd(month,2,DateAdd(Year, yr-1900, 0))`? [duplicate] - sql-server

This question already has answers here:
DATEADD equivalent in PostgreSQL [duplicate]
(1 answer)
Equivalence of DATEADD in PostgreSQL?
(1 answer)
Adding months to a date with dateadd
(1 answer)
Adding one year to a date field in postgresql
(2 answers)
DATE ADD function in PostgreSQL
(2 answers)
Closed 21 days ago.
I met this line during the census of the project from SQL Server to PostgreSQL
I can't figure out what it's doing?
What is this DateAdd(month,2,DateAdd(Year, yr-1900, 0))?
declare #LastMartSundaysForDelete table(date datetime)
insert into #LastMartSundaysForDelete
select dateadd(hour,3,cast(dateadd(day,1-datepart(weekday,eomonth(date)),eomonth(date)) as datetime))
from
(
select DateAdd(month,2,DateAdd(Year, yr-1900, 0)) date
from
(select distinct year(date) yr from #source) ta
)tb
I did this with the help of the Internet but it doesn't work
INSERT INTO lastmartsundaysfordelete
SELECT ((date_trunc('month', date) + interval '1 month' - interval '1 day' + (1 - date_part('weekday',date_trunc('month', date) + interval '1 month' - interval '1 day'))* INTERVAL '1 day' )::TIMESTAMP+ 3 * INTERVAL '1 hour')
FROM
(
SELECT(((0000-00-00)::TIMESTAMP +(ta.yr-1900)* INTERVAL '1 Year') + 2 * INTERVAL '1 month') as date
FROM(
select distinct date_part('year', date) AS yr
from v_source_table as ty
) AS ta
) AS tb
;

Related

SQL converting month into Years and Months

I have an X number of months, but I need to break it into xx years yy months in SQL.
For example: 31 months should be 2 years 7 months.
Is there any inbuilt function or something to help?
Many thanks for your help.
You can use modulus to get the months and floor to get the years
SELECT totalmonths, FLOOR(tottalmonths / 12) AS years, totalmonths % 12 as months
FROM -- ...
You can try this:
SELECT
(months_column_name / 12) AS years,
(months_column_name % 12) AS months
FROM table_name
You can create a solution the uses built-in functions, but I'd hardly call it helpful when olde fashioned arithmetic operators will provide the desired results in a much more concise manner, e.g. Hogan's answer. dbfiddle.
with
SomeMonths as (
-- Create some test data from 0 to 100.
select 0 as Months
union all
select Months + 1
from SomeMonths
where Months < 100 ),
CompleteDate as (
-- Convert the number of months into a date based at 1 January 1.
select Months, DateAdd( month, Months, Cast( '00010101' as Date ) ) as Sometime
from SomeMonths )
select Months,
-- Make the number of years zero-based.
Year( Sometime ) - 1 as TheYears,
-- Make the number of months zero-based.
Month( Sometime ) - 1 as TheMonths
from CompleteDate;
Hi there Unknown Coder,
I made some code here that will display the number of months and years..
It also has a more human friendly way of displaying the data, like in your example.
So that last one will display as "2 years 7 months" if your value was 31.
Here's my code with the temp database for testing:
Declare #monthtest TABLE
(
NumOfMonths int
);
INSERT INTO #monthtest (NumOfMonths) select 11
INSERT INTO #monthtest (NumOfMonths) select 13
INSERT INTO #monthtest (NumOfMonths) select 31
select
cast(x1.NumOfMonths / 12 as int) as years,
(x1.NumOfMonths ) % 12 as months,
concat(
cast(x1.NumOfMonths / 12 as int),
(case when cast(x1.NumOfMonths / 12 as int) = 1 then ' year ' else ' years ' end ),
(x1.NumOfMonths ) % 12,
(case when (x1.NumOfMonths ) % 12 = 1 then ' month' else ' months' end )
) as combined
from #monthtest as x1
This will output as
years
months
combined
0
11
0 years 11 months
1
1
1 year 1 month
2
7
2 years 7 months

Retrieve data 14 days prior to their "date of manufacture" irrespective of Year in SQL Server

I need all the rows that are 14 days next to my current date and that should not depend upon the Year. For example if today is 2nd of September, then the query should return all the rows of which u_dateofmanufacture is (2+14) 16th September, no matter which year it belongs. the focus is only on the date and the month.
I have also attached the screenshot and the column "date of Manufacture" is highlighted.
According to the screenshot only the rows 2,3 and 4 should be returned. They all have different year but the day and month is same(09-16).
I am using SQL Server.
declare #date DATE = dateadd(d,14,getdate())
select * from your table where month(u_dateofmanufacture)= month(#date) and day(u_dateofmanufacture) = day(#date)
You have a problem with leap years and the first 14 days of the year. If we skip these problems, you can use:
where month(datecol + 14) * 100 + day(datecol + 14) >= month(getdate()) * 100 + day(getdate()) and
month(datecol) * 100 + day(datecol) < month(getdate()) * 100 + day(getdate())
I would use a join on a virtual table containing all the possible years
SELECT t.*
FROM YourTable t
JOIN (
SELECT
starting = DATEADD(day, -14, DATEFROMPARTS(v.year, MONTH(GETDATE(), DAY(GETDATE())),
ending = DATEFROMPARTS(v.year, MONTH(GETDATE(), DAY(GETDATE()))
FROM (VALUES
(2023),(2022),(2022),(2021),(2020),(2019),(2018),(2017),(2016),(2015),(2014),(2013),(2012),(2011)
) v(year)
) v ON t.u_dateofmanufacture >= v.starting
AND t.u_dateofmanufacture < v.ending
you can use a query like below
select * from yourtable
where month(u_dateofmanufacture)= month(dateadd(d,14,getdate()))
and day(u_dateofmanufacture) =day(dateadd(d,14,getdate()))
optimally
declare #seekdate = dateadd(d,14,getdate())
select * from yourtable
where month(u_dateofmanufacture)= month(#seekdate )
and day(u_dateofmanufacture) =day(#seekdate)

SQL Server : selecting 'WEEKDAY' part by passing date in 'ddd' format

How I can retrieve 'WEEKDAY' part by passing 'ddd' format in SQL Server?
For example in if I pass 'tue' and the response will be 3, beacuse
1 - Sunday
2 - Monday
3 - Tuesday
... like that.
I get the 'WEEKDAY' of current date by executing following query.
select DATEPART(WEEKDAY, GETDATE())
This will return the day number for the given short day name honouring the current DATEFIRST setting.
--Example day name
DECLARE #Day CHAR(3) = 'Tue'
SELECT
DATEPART(WEEKDAY,DATEADD(DAY, Number, GETDATE())) DayNumber
FROM
master..spt_values N
WHERE
N.type = 'P' AND N.number BETWEEN 1 AND 7
AND DATENAME(WEEKDAY,DATEADD(DAY, Number, GETDATE())) LIKE #Day+'%'
You can try similar to this
SELECT *
FROM (
SELECT 1 PK ,'Sunday' Value UNION
SELECT 2,'Monday' UNION
SELECT 3,'Tuesday' UNION
...
SELECT 7,'Saturday'
) T WHERE T.[Value] LIKE '%tue%'
Try this:
SELECT datepart(weekday,getdate()), datename(dw, getdate())
This will return the weekday and name of that day considering ISO_WEEK rule
More detail here
this will give you the weekday no that is not dependant on ##datefirst or langauge setting
select [weekday] = case #weekday_name
when 'Sun' then (7 - ##datefirst + 0) % 7 + 1
when 'Mon' then (7 - ##datefirst + 1) % 7 + 1
when 'Tue' then (7 - ##datefirst + 2) % 7 + 1
when 'Wed' then (7 - ##datefirst + 3) % 7 + 1
when 'Thu' then (7 - ##datefirst + 4) % 7 + 1
when 'Fri' then (7 - ##datefirst + 5) % 7 + 1
when 'Sat' then (7 - ##datefirst + 6) % 7 + 1
end

Filter rows by specific interval

I have the following DateTime values in a table, I need to filter the set only if there was a gap between this value > 5 seconds. This should be for a specific date, starting with the first row.
Any idea how to do it only in SQL using SQL Server 2012?
1 2014-04-02 05:33:56.60
2 2014-04-02 05:40:01.55
3 2014-04-02 05:52:45.81
4 2014-04-02 05:52:47.50
5 2014-04-02 06:35:48.84
6 2014-04-02 06:50:49.72
7 2014-04-02 07:01:02.71
8 2014-04-02 07:01:04.35
9 2014-04-02 07:01:09.29
10 2014-04-02 07:44:05.71
11 2014-04-02 08:37:47.06
In SQL Server 2012 you can use lead function, Try following
;with cte as
(
select id, d, datediff(s, d, lead(d) over(order by d)) as diff from Test
)
select * from cte where diff > 5
you can use it like this
WITH rows AS
(
SELECT *, ROW_NUMBER() OVER (ORDER BY InputDate) AS rn
FROM given_table
)
SELECT DATEDIFF(second, mc.InputDate, mp.InputDate)
FROM rows mc
JOIN rows mp
ON mc.rn = mp.rn - 1
where DATEDIFF(second, mc.InputDate, mp.InputDate)> 5
You can use the lead function to get the next date and datediff to calculate the seconds difference, then filter for your criteria.
with cte as
(
select id, date, diff = datediff(s, date, lead(date) over(order by date)
from tbl
)
select * from cte where diff > 5
Hope this will also help you.
DECLARE #TAB TABLE (ID INT,DT DATETIME)
INSERT INTO #TAB VALUES
(1 ,'2014-04-02 05:33:56.60'),
(2 ,'2014-04-02 05:40:01.55'),
(3 ,'2014-04-02 05:52:45.81'),
(4 ,'2014-04-02 05:52:47.50'),
(5 ,'2014-04-02 06:35:48.84'),
(6 ,'2014-04-02 06:50:49.72'),
(7 ,'2014-04-02 07:01:02.71'),
(8 ,'2014-04-02 07:01:04.35'),
(9 ,'2014-04-02 07:01:09.29'),
(10,'2014-04-02 07:44:05.71'),
(11,'2014-04-02 08:37:47.06')
--Query
SELECT A.*,B.*
FROM #TAB A,#TAB B
WHERE A.ID = B.ID - 1
AND DATEDIFF(SECOND,A.DT,B.DT) > 5
--Result

Selecting all rows more than 24 hours old in PostgreSQL [duplicate]

I have a timestamp field in a postgres database. I would like to select all dates that have happened within the last month. So something like select * from table where timestamp > (current timestamp - 1 month).
select * from table where timestamp > now() - interval '1 month'
To be precise:
SELECT *
FROM tbl
WHERE ts_col > now() - interval '1 month'
AND ts_col <= now();

Resources