Select the last 7 days of each month - sql-server

I am using SQL Server 2008. I'm looking to bring back only the last 7 calendar days of each month, how would I go about doing this.
Thanks

assuming field called logtime, get the range with
....where logtime BETWEEN dateadd(month,month(logtime),dateadd(year, year(logtime) - 1900,0)) - 7
AND
dateadd(month,month(logtime),dateadd(year, year(logtime) - 1900,0)) - 1;
you also need to check that 'logtime' (replaced by your field name) is in the range of dates you are also selecting from e.g ...AND(YEAR(logtime)) = 2016 ..for example

Try this
SELECT
*
FROM
Payments P
WHERE
P.PaymentDay < (SELECT DATEADD(month, ((YEAR(P.PaymentDay) - 1900) * 12) + MONTH(P.PaymentDay), -1)) AND -- Last day of current year-month
P.PaymentDay > (SELECT DATEADD(month, ((YEAR(P.PaymentDay) - 1900) * 12) + MONTH(P.PaymentDay), -7)) -- Last 7. day of current year-month

Some specific examples and direction would help. If you just want rows where, say columnA contains a date that falls within the last 7 days of it's respective month, then you can simply say:
WHERE month(columnA) != month(dateadd(day,7,columnA))
I.e. it asks the question, "given a date, A, does the date 7 days later fall in a different month?"
Note that neither this query nor those include in other answers is able to make use of indexes on this column (since we're using it as an input to a calculation), which is a shame.

Try this:
--DAY(DATE) as day_of_month from day_master table.
select
a.day_id,a.day_of_month
from day_master a LEFT JOIN (select max(day_of_month) as 'max_day_of_month',day_id,month_no,year_no from day_master group by month_no,year_no)b ON b.month_no=a.month_no and a.year_no=b.year_no
where (b.max_day_of_month-a.day_of_month)<7 and a.month_no=11 and a.year_no=2017
GROUP BY a.month_no,a.year_no,a.day_id;

Related

Where condition based on month and year

i have the following code:
select COUNT(STL.ITEID)
from STORETRADELINES STL
left join FINTRADE FT ON STL.FTRID=FT.ID
where RIGHT(CONVERT(datetime, FT.FTRDATE, 3), 5) < RIGHT(CONVERT(datetime, GETDATE(), 3), 5)
and FT.FTRDATE > CONVERT(datetime,'01.01.2017',103)
I want to select all the documents that fall between 01.01.2017 and 30.04.2017 (always, the last day of the previous month).
Seem's that this way is not good, because is returning all the docs from 01.01 until today.
Where am i wrong ? Btw, i use sql server 2008.
Thank you
The problem is, you're doing string comparisons. Use date comparisons instead:
select COUNT(STL.ITEID)
from STORETRADELINES STL
left join FINTRADE FT ON STL.FTRID=FT.ID
where FT.FTRDATE < DATEADD(month,DATEDIFF(month,0,GETDATE()),0)
and FT.FTRDATE >= '20170101'
Here, the DATEADD/DATEDIFF pair of calls are rounding the current date down to the start of the current month.
You can use a similar DATEADD/DATEDIFF pair for your start-of-period condition, using year instead of month if you want this query to be generic for any current year
The reason you're "stringly-typed" code doesn't work is that your CONVERT calls are converting datetime values to datetime. The style parameter is ignored here since datetimes don't have a format. You then get an uncontrolled implicit conversion of the datetimes into varchar so that RIGHT can work, and it's that conversion that you should have tried to control.
As it is, this:
select RIGHT(CONVERT(datetime, GETDATE(), 3), 5)
Generates:
:50AM
Which you can hopefully see is nothing like what you wanted.
dateadd(mm,datediff(mm, 0 , current_timestamp),0) will return the first day of current month.
Your query could be
SELECT COUNT(STL.ITEID)
FROM STORETRADELINES STL
left join FINTRADE FT ON STL.FTRID=FT.ID
where
FT.FTRDATE >= '2017-01-01' AND FT.FTRDATE < dateadd(mm,datediff(mm, 0 , current_timestamp),0)

How to get max date of previous year in a dataset with a window-function in SQL Server

I have a simple table with just a DATETIME filed.
My question is, how can I get the value related to the end-of-year of previous year, with a window-function query?
I've tried with this query but the result is the end-of-year of the current year:
SELECT datefield, max(datefield) OVER (PARTITION BY YEAR(datefiled)) FROM foo
I am using SQL Server 2012.
Many thanks to all.
If you want to filter records then you need to use Where clause. You need something like this not window function.
SELECT TOP 1 WITH ties *
FROM foo
WHERE datefield <= Datefromparts(Year(Getdate()) - 1, 12, 31)
ORDER BY datefield DESC
or
SELECT *
FROM foo
WHERE datefield = (SELECT Max(datefield) AS last_date_prev_year
FROM foo
WHERE datefield <= Datefromparts(Year(Getdate()) - 1, 12, 31))
I don't think you need to use a windowed function. A simple filter combined with the max function will return the end of the previous year.
-- Where clause removes records from current and future years.
SELECT
MAX(datefield)
FROM
foo
WHERE
YEAR(datefield) < YEAR(GETDATE())
;
Although simple, this approach has a small problem. Using the year function, on datefield in the where clause, makes the query non-sargable. If performance is an issue; you could fix by using DateFromParts as demonstrated in #Prdp's fine answer.
EDIT
This version of the query uses a windowed function, as requested by the OP.
-- Max of previous year, using a windowed function.
SELECT
MAX(datefield) AS LastYearEnd
FROM
(
-- Rank records based on year.
-- Current year is 1, last year is 2, etc.
SELECT
datefield,
DENSE_RANK() OVER (ORDER BY YEAR(datefield) DESC) AS rn
FROM
foo
) AS dr
WHERE
rn = 2
;
The above only returns one record. If you want see the last day of the previous year, next to every record in your table:
-- Returns last day of previous year, relative to dateField.
SELECT
datefield,
DATEADD(YEAR, -1, MAX(datefield) OVER (PARTITION BY YEAR(datefield)))
FROM
foo
;

Access SQL: How to select dates after today if current year, else select all dates

Im working on a query where if the records in a table are from the current year, i need only to select records whose day and month are equal or greater than the current date. Otherwise (if the year is greater) I need to select all dates.
I was thinking of using the iif function or conditions on the where clause but im not close at at all.
For example
SELECT IFF(YEAR(FECHAPAGO) = YEAR(DATE()), MONTO WHERE MONTH(FECHAPAGO) >= MONTH(DATE), MONTO) FROM CUPONES
or
SELECT MONTO FROM CUPONES WHERE IF YEAR(FECHAPAGO) = YEAR(DATE()) ...
I apologize if im not being clear enough but im having trouble putting it to words. If any clarification is needed Ill be happy to rephrase my question.
Thanks in advance
You can do it with straight logic;
select monto from cupones where (year(fechapago) = year(date() and (month(fechapago) > month(date()) or (month(fechapago) == month(date() and day(fechapago) > day(date()))( or (year(fechapago()) > year(date()))

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.

How to turn separate year, month and day columns into a single date?

I have a year column that contains things like 2013, 2012, etc. A month column that displays 1-12, and a day column that contains 1-31. I need to run a select that concatenates them and casts them as an actual date, but I am unsure how to go about this. Can anyone provide some input?
For SQL Server 2008+:
SELECT CONVERT(DATE,CAST([Year] AS VARCHAR(4))+'-'+
CAST([Month] AS VARCHAR(2))+'-'+
CAST([Day] AS VARCHAR(2)))
For SQL Server 2005:
SELECT CONVERT(DATETIME,CAST([Year] AS VARCHAR(4))+
RIGHT('00'+CAST([Month] AS VARCHAR(2)),2)+
RIGHT('00'+CAST([Day] AS VARCHAR(2)),2))
In SQL Server 2012, you will probably be better off avoiding string concatenation or complicated math, as they created a function seemingly just for you:
SELECT DATEFROMPARTS(2013, 8, 19);
Of course, storing the data wrong in the first place can lead to problems - for example, what constraint prevents y = 2013, m = 2 and d = 31 from being in the table? You'd think you could wrap that with TRY_CONVERT(), but not so much:
SELECT TRY_CONVERT(DATE, DATEFROMPARTS(2013, 2, 31));
Error:
Msg 289, Level 16, State 1, Line 3
Cannot construct data type date, some of the arguments have values which are not valid.
So, in order to prevent bad data from getting into these three columns, you will need to use one of the above cumbersome approaches in a check constraint or a trigger...
...or...
...in any version, you could fix the table and store a date (or datetime) in the first place. You get all the benefits of automatic validation as well as intrinsic date/time functionality that you don't get with three separate unrelated integers. Much better off pulling the parts out when you need them separately (with computed columns, a view, or at query time) from a value that is guaranteed to be a date, than try to rely on the individual parts to form a valid date...
SELECT CAST(STR(10000 * Year + 100 * Month + Day) AS DATETIME)
One more, just to fill up list of various approaches:
select
dateadd(d, t.d-1, dateadd(m, t.m-1, dateadd(yy, t.y-1900, 0)))
from (values
(2011, 10, 26)
,(2012, 1, 5)
,(2013, 7, 15)
) t(y, m, d)
You could try something like this if your columns are character columns
Select Cast([year] + '-' + [month] + '-' + [day] as datetime)
From yourTable
If they are numeric you'll need to cast each column to varchar before concatenating otherwise you'll end up getting something funky
Use the Convert function
Select Convert(datetime ,YEAR + '/' + MM + '/' + DAY)
Replace YEAR with your year column, MM with month, and DAY with your day column. and concatenate to formulate your date string

Resources