I want to check what are the bookings in the last 2 days of each month, I already did for the last day but I gives me some wrong data, and I need to expand it to get not only the last day but also the last 2 days of each month
SELECT Debit, Amount, Posted_Date, Posted_Time, Posted_By
FROM [dbo].[Test_data]
WHERE Booking_date IN (
SELECT MAX(Booking_date)
FROM [dbo].[Test_data]
GROUP BY MONTH(Booking_date), YEAR(Booking_date)
)
This will give you all the bookings made on the last 2 days of the month of booking. It won't work if booking_date stores time.
SELECT Debit, Amount, Posted_Date, Posted_Time, Posted_By
FROM [dbo].[Test_data]
WHERE Booking_date between
DATEADD(MONTH, DATEDIFF(MONTH, 0, Booking_date) + 1, 0) - 2 AND
DATEADD(MONTH, DATEDIFF(MONTH, 0, Booking_date) + 1, 0) - 1
If you are storing time on booking_date:
SELECT Debit, Amount, Posted_Date, Posted_Time, Posted_By
FROM [dbo].[Test_data]
WHERE Booking_date >= DATEADD(MONTH, DATEDIFF(MONTH, 0, Booking_date) + 1, 0) - 2 AND
Booking_date < DATEADD(MONTH, DATEDIFF(MONTH, 0, Booking_date) + 1, 0)
One more approach is using a calendar table ,once you have calendar table which looks like below,then it is very easy to get all the info
Above calendar table gives me the required dates all you have to do is join next
select t1.* from
dbo.testdate t1
join
(select date from calendar
where date>=convert(datetime,dateadd(day,-1,LDtOfMo)) and year=2013
) c
on c.date=t1.booking_Date
SQL Server has a new date function named SQL EOMonth() for calculating end of month
EOMONTH (getdate())
After you get the end of month, you can use following for the day before
DATEADD(dd,-1,@eomonth_date)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.