This article is a mirror article of machine translation, please click here to jump to the original article.

View: 10825|Reply: 0

[Source] Practical SQL statement: date estimation

[Copy link]
Posted on 11/26/2014 3:53:01 PM | | |

DECLARE @dt datetime
SET @dt=GETDATE()

DECLARE @number int
SET @number=3

--1. Specify the date of the first or last day of the year
--A. The first day of the year
SELECT Co nVERT(char(5),@dt,120)+ '1-1 '

--B. The last day of the year
SELECT Co nVERT(char(5),@dt,120)+ '12-31 '


--2. The first or last day of the quarter in which the specified date is located
--A. First day of the quarter
SELECT Co nVERT(datetime,
Co nVERT(char(8),
DATEADD(Mo nth,
DATEPART(Quarter,@dt)*3-Mo nth(@dt)-2,
@dt),
120)+ '1 ')

--B. Last day of the quarter (CASE judgment)
SELECT Co nVERT(datetime,
Co nVERT(char(8),
DATEADD(Mo nth,
DATEPART(Quarter,@dt)*3-Mo nth(@dt),
@dt),
120)
+CASE WHEN DATEPART(Quarter,@dt) in(1,4)
THEN  '31 'ELSE  '30 ' END)

--C. Last day of the quarter (direct push algorithm)
SELECT DATEADD(Day,-1,
Co nVERT(char(8),
DATEADD(Mo nth,
1+DATEPART(Quarter,@dt)*3-Mo nth(@dt),
@dt),
120)+ '1 ')


--3.The first or last day of the month in which the specified date is located
--A. The first day of the month
SELECT Co nVERT(datetime,Co nVERT(char(8),@dt,120)+ '1 ')

--B. The last day of the month
SELECT DATEADD(Day,-1,Co nVERT(char(8),DATEADD(Mo nth,1,@dt),120)+ '1 ')

--C. Last day of the month (easy to use wrong method)
SELECT DATEADD(Mo nth,1,DATEADD(Day,-DAY(@dt),@dt))


--4. Any day of the week in which the specified date is located
SELECT DATEADD(Day,@number-DATEPART(Weekday,@dt),@dt)


--5. Any day of the week in which the specified date is located
--A.  Sunday as the first day of the week
SELECT DATEADD(Day,@number-(DATEPART(Weekday,@dt)+@@DATEFIRST-1)%7,@dt)

--B.  Monday is the first day of the week
SELECT DATEADD(Day,@number-(DATEPART(Weekday,@dt)+@@DATEFIRST-2)%7-1,@dt)






Previous:Index utilization problem when sqlserver handles like '%keyword%'
Next:ORACLE 11g New Features - Allows DDL locks to wait for DML locks
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com