SQL Server Finding date in between - sql-server

I have table like below,
In Realtime scenario I have more rows for testing purpose I am attaching only two rows.
[Table]
Value
Start Date
End Date
10
30-Jun-15
30-Jun-16
20
30-Jun-16
31-Oct-16
If I requested start date as ' 31-JUL-2016' and end date as '31-AUG-2016',
I need to get only row 2(Second row from table) in above table.
If I requested start date as ' 31-AUG-2015' and end date as '31-AUG-2016',
I need get all two rows (All row from table) in above table.
How I can achieve this in SQL Server?

SELECT * FROM your_table
WHERE '20160731' <= EndDate
AND '20160831' >= StartDate;
SELECT * FROM your_table
WHERE '20150831' <= EndDate
AND '20160831' >= StartDate;

Related

SQL Server : update every 5 records with Past Months

I want to update 15 records in that first 5 records date should be June 2019,next 5 records with July 2019,last 5 records with Aug 2019 based on employee id,Can any one tell me how to write this type of query in SQL Server Management Studio V 17.7,I've tried with below query but unable to do for next 5 rows..
Like below query
Update TOP(5) emp.employee(nolock) set statusDate=GETDATE()-31 where EMPLOYEEID='XCXXXXXX';
To update only a certain number of rows of a table you will need to include a FROM clause and join a sub-query which limits the number of rows. I would suggest using OFFSET AND FETCH instead of top so that you can skip X number of rows
You will also want to use the DATEADD function instead of directly subtracting a number from the DateTime function GETDATE(). I'm not certain but I think your query will subtract milliseconds. If you intend to go back a month I would suggest subtracting a month rather than 31 days. Alternatively it might be easier to specify an exact date like '2019-06-01'
For example:
TableA
- TableAID INT PK
- EmployeeID INT FK
- statusDate DATETIME
UPDATE TableA
SET statusDate = '2019-06-01'
FROM TableA
INNER JOIN
(
SELECT TableAID
FROM TableA
WHERE EmployeeID = ''
ORDER BY TableAID
OFFSET 0 ROWS
FETCH NEXT 5 ROWS ONLY
) T1 ON TableA.TableAID = T1.TableAID
Right now it looks like your original query is updating the table employee rather than a purchases table. You will want to replace my TableA with whichever table it is you're updating and replace TableAID with the PK field of it.
You can use a ROW_NUMBER to get a ranking by employee, then just update the first 15 rows.
;WITH EmployeeRowsWithRowNumbers AS
(
SELECT
T.*,
RowNumberByEmployee = ROW_NUMBER() OVER (
PARTITION BY
T.EmployeeID -- Generate a ranking by each different EmployeeID
ORDER BY
(SELECT NULL)) -- ... in no particular order (you should supply one if you have an ordering column)
FROM
emp.employee AS T
)
UPDATE E SET
statusDate = CASE
WHEN E.RowNumberByEmployee <= 5 THEN '2019-06-01'
WHEN E.RowNumberByEmployee BETWEEN 6 AND 10 THEN '2019-07-01'
ELSE '2019-08-01' END
FROM
EmployeeRowsWithRowNumbers AS E
WHERE
E.RowNumberByEmployee <= 15

SQL Server - Check date field between two dates in where clause

In the following query the date returned is 2019-07-12 14:12:58.253
SELECT MAX(fileDate) AS maxdate FROM filetable
This query returns the following value 2019-07-11 23:46:20.317
SELECT MAX(fileDate) AS maxdate FROM filetable WHERE fileDate BETWEEN '2019-01-18' AND '2019-07-12'
I have tried using >= and <= instead of BETWEEN with the same results.
Why is this happening?
'2019-07-12' against a datetime will be implicitly converted to the datetime 2019-07-12T00:00:00.000. For your query with the WHERE clause fileDate BETWEEN '2019-01-18' AND '2019-07-12' that means that a value like 2019-07-12T14:12:58.253 is outside of the range, as it's larger than 2019-07-12T00:00:00.000.
The common way is to use >= and < where the value for the < is the day after the day you need. Therefore you end up with the below:
SELECT MAX(fileDate) AS maxdate
FROM filetable
WHERE fileDate >= '2019-01-18'
AND fileDate < '2019-07-13';

How to check date time column value equals to current date in sql where clause

I have a date time column in sql DB - named check_time. I want to write a select query where this check_time should be equals to today's date (no need to consider what time is. Only need to check current date).
For example check_time in table is inserted as 03/08/2017 12:00:00.000 AM.
I have written like below
SELECT * FROM time_details
WHERE check_time = DATEADD(day, DATEDIFF(day,0,GETDATE()),0)
But it returns nothing.
This is the correct syntax:
SELECT * FROM time_details where (DATEDIFF(d, check_time, GETDATE()) = 0)
Just CAST the today's date to DATE.
Query
select * from time_details
where check_time = cast(getdate() as date);
Try with
SELECT * FROM time_details where DATE(check_time) =CURDATE()
The DATE function is going to extract just the date from you datetime field while the CURDATE is returning the current date.
Check with the sql query
SELECT * FROM time_details where DATE(check_time)=DATE(NOW())
this should work
SELECT * FROM time_details where check_time =convert(varchar, getdate(), 101)

selecting records from a table where a given date falls between 2 dates (columns) from a table in SQL Server

EDIT -----------------
I'm going to try to clarify.
I have this table:
A user will input a start date and an end date.
Let's say the user inputs 2011-10-21 for the start and 2011-12-18 for the end.
This will bring back all the records:
But what if the user inputs 2011-10-22 and 2011-12-18?
The 2011-10-22 is BETWEEN the date range of the FIRST ROW 2011-10-21 (start) & 2011-10-23 (end).
SINCE IT IS BETWEEN THE DATE RANGE OF THE FIRST RECORD, I WANT to return that row as well. I DO NOT WANT TO EXCLUDE IT.
So if if I run a query like this:
select * from table where PayPeriodStart between '2011-10-22' and '2011-12-18'
I WANT to see this:
and NOT this:
PLEASE NOTE... the user can enter in any start or end date and it'll be at least 1 week.
So they can pick 2011-11-09 (start) and 2011-12-04 (end) for example.
You'll want the search criteria to return the rows where the period start date is before the end date criteria and the period end date is after the start date criteria. In other words:
declare #Table table (PayPeriodStart smalldatetime, PayPeriodEnd smalldatetime)
insert into #Table (PayPeriodStart, PayPeriodEnd)
select '2010-01-01', '2010-12-31' -- test before the criteria; is not returned
union select '2011-10-21', '2011-10-23' -- overlaps start date; is returned
union select '2011-10-24', '2011-11-06' -- fully in date range; is returned
union select '2011-11-07', '2011-11-20' -- fully in date range; is returned
union select '2011-11-21', '2011-12-04' -- fully in date range; is returned
union select '2011-12-05', '2011-12-18' -- overlaps end date; is returned
union select '2012-01-01', '2012-12-31' -- test after the criteria; is not returned
-- This yields all but the first row
select * from #Table where PayPeriodStart between '2011-10-22' AND '2011-12-10'
-- This will yield all the rows that overlap the search criteria
select * from #Table
where PayPeriodStart <= '2011-12-10' -- the end search date
and PayPeriodEnd >= '2011-10-22' -- the start search date
If you are looking for all records that are valid between '2011-10-22' AND '2011-12-10' , this is the query you should use
select * from table where ('2011-10-22' >= PayPeriodStart AND '2011-10-22' <= PayPeriodEnd) Or ('2011-10-22' < PayPeriodStart AND '2011-12-10' > PayPeriodEnd)
I have never been a fan of the between syntax for the edge case reason, so I tend to use this syntax instead:
select * from table where ('2011-10-22' <= PayPeriodStart AND PayPeriodStart <= '2011-12-10')
Same end result, but I can ensure I include the boundaries as needed.
Are you asking for
select * from table where '2011-10-22' between PayPeriodStart AND PayPeriodEnd
AND '2011-12-10' between PayPeriodStart AND PayPeriodEnd
If you want to get data based on first of the month and last of the month or for fixed time interval like 30 day window, you may have to use DateAdd, DateDiff functions to calculate dates.
Following example is based on FirstOfTheMonth, LastOfTheMonth calculation
your reference data
declare #refDate date = getdate()
select #min = dateadd(mm, datediff(mm, 0, #refDate), 0) -- First of the month
, #max = dateadd(dd, -1, dateadd(mm, datediff(mm, 0, #refDate) + 1, 0)) --Last of the month

Loop through month in SQL Server

Every year we have 12 month. I should write a query that select in one table for every month. For example I should make report that show me every month transaction count.
I did it but in wrong way.
I wrote 12 query for every month.
Like this :
SET #MONTH12M = (SELECT SUM(Amount) AS TOT
FROM [fidilio].[dbo].[CardTransactionLog] CL
JOIN CardTransaction CT ON CT.CardTransactionLogId = CL.CardTransactionLogId
WHERE (cl.TransactionPersianTimeStamp > N'1393/12/01'
AND cl.TransactionPersianTimeStamp< N'1393/12/31')
)
INSERT INTO #TEMP(MonthValue, CountValue, TypeValue)
SELECT
12,
CASE WHEN #MONTH12M IS NULL THEN 0 ELSE #MONTH12M END,4
I have 11 more query like that.
Finally I fetch my result I put in temp table .
How can I do this dynamically?
How can I do it with loop ?
You can use group by to generate statistics per month:
select month(date_column)
, sum(amount)
from YourTable
group by
month(date_column)
The T-SQL function month extracts the numeric month from a datetime column.

Resources