How do I get the number of days in a month for the specific date in that row of data using SQL? - sql

For example, if I have a data set including two columns, one which shows the month as a number and the other which shows the year (result of grouping my data using GROUP BY), I want to add another column called 'Days in the month' which will display the number of days in the respective month. Is there a way I can do this? Is there some function I can add in the SELECT clause?
I want to do this since there are further calculations I need to do with that number for each row.

In SQL Server 2012+, you can use:
select day(eomonth(datecol))
eomonth() gets the last day of the month. day() just returns the day of the month -- the number of days in the month, in this case.

For older SQL Server versions, I use the following:
DAY(DATEADD(MONTH, DATEDIFF(MONTH, -1, date_column)- 1, -1))
Much less elegant than the previous answer, but functional.

Related

SQL calculate number of days in month excluding weekends and holidays days

I have approximately the same table (excluding count column). I want to calculate the number of working days (Mon-Fri) and exclude public holidays.
I tried to try the following query
SELECT count(distinct(date)) from MYDB where dummy <> 1
However, it gives the only total number of days including weekends. Additionally, if use this command it counts distinct dates, however, my dates do not show a full month, so another logic should've used. Could you help to figure out which code is better to use?
there should be a function in Vertica that extracts weekday from date, so to exclude weekends you'll need to add another condition like
extract(dow from date) not in (6,0)
(6 is Sat, 0 is Sun in this case)

How to round up a month-date based on certain parameters

I need to round up a month-date based on certain parameters. For example: If I have a parameter where if a day in a given month is between the 6th and the 4th of the next month, I need my query to return the next months date. Is there a way to round up the month given these parameters without hard coding case whens for every single month ever?
SELECT case when date_trunc('day',li.created_at between '2019-03-06 00:00:00' and '2019-04-06 00:00:00' then '2019-04-01' end)
FROM line_items li
If you want the beginning of the month, but offset by 4 days, you can use date_trunc() and subtract some number of days (or add some number of days). You seem to want something like this:
select dateadd(month, 1, date_trunc('month', li.created_at - interval '4 day'))
Another approach is to create a canonical "dates" table that precomputes the mapping from a given date to a new date using your rounding scheme. The mapping could be done outside of redshift in a script and the table loaded in (or within redshift using a user defined function).

T-SQL: How to get all records prior to the first day of the current month?

Using SQL Server: I am trying to find all records prior to the first day of the current month and set this as a parameter in an SSRS report (so I can't use a static value).
So, I need all records prior to the first day of the each current month going forward in column CREATEDDATETIME ('yyyy-mm-dd').
I have seen a lot of threads on how to find records for a specific month and various other searches but none specifically related to the above. Interested to see if the EOMONTH function will be of use here.
Thanks for the help and advice.
Here is an expression to use EOMONTH() function with optional parameter -1.
Explanations:
DateAdd: add 1 day to expression
getdate is current date
EOMONTH is end day of a given month; however, if you put an optional integer -1, this would mean last month
Thus: first day of current month is add one day to end of day last month
SELECT DATEADD(DAY,1,EOMONTH(getdate(),-1));
Result: 2018-04-01
SO in your query:
select *
from table
where CREATEDDATETIME < DATEADD(DAY,1,EOMONTH(getdate(),-1));
I would use datefromparts():
select t.*
from t
where CREATEDDATETIME < datefromparts(year(getdate()), month(getdate()), 1);
There's already two other answers that work, but for completeness here is a third common technique:
SELECT *
FROM [table]
WHERE CREATEDDATETIME < dateadd(month, datediff(month,0, current_timestamp), 0)
You might also get answers suggesting you build the date using strings. Don't do that. It's both the least efficient and most error prone option you could use.
all three answers are great, how ever you may find that it will select all the data prior to the 1st day of the current month until the 1st Createdate. This could cause the report to take forever to run, Maybe building in a limitation to the code I would use something like this to build a report that gives details for last month only.
Select [columns]
from [source]
where [Createdate] between
/*First day of last Month*/
DATEADD(mm, DATEDIFF(mm, 0, Getdate())-1, 0 and
/*First day of this Month*/
dateadd(mm,datediff(mm,0,Getdate()),0)

Wrong US week number calculation for 1st jan using datepart

SQL server DATEPART function has two options to retrieve week number;
ISO_WEEK and WEEK. I Know the difference between the two, I want to have week numbers based on Sunday start standard as followed in the US; i.e. WEEK. But it doesn't handles partial weeks the way I expected. e.g.
SELECT DATEPART(WEEK,'2015-12-31') --53
SELECT DATEPART(WEEK,'2016-01-01') --1
SELECT DATEPART(WEEK,'2016-01-03') --2
gives two different week numbers for a single week, divided in two years. I wanted to implement something like in the following link for week days.
Week numbers according to US standard
Basically I would like something like this;
SELECT DATEPART(WEEK,'2015-12-31') --1
SELECT DATEPART(WEEK,'2016-01-01') --1
SELECT DATEPART(WEEK,'2016-01-03') --2
EDIT:
Basically I am not good with the division of a single week into two, I have to perform some calculations based on week numbers and the fact that a single week to be divided isn't acceptable. So if above isn't possible.
Is it possible that the week number one would start from 2016-01-03. i.e. what I would in that case would be something like this:
SELECT DATEPART(WEEK,'2015-12-31') --53
SELECT DATEPART(WEEK,'2016-01-01') --53
SELECT DATEPART(WEEK,'2016-01-03') --1
If you want the US numbering, you can do this by taking the WEEK number of the end of the week rather than the date itself.
First ensure that the setting for first day of the week is in fact Sunday on your system. You can verify this by running SELECT ##DATEFIRST; this should return 7 for Sunday. If it doesn't, run SET DATEFIRST 7; first.
SELECT
end_of_week=DATEADD(DAY, 7-(DATEPART(WEEKDAY, '20151231')), '20151231'),
week_day=DATEPART(WEEK, DATEADD(DAY, 7-(DATEPART(WEEKDAY, '20151231')), '20151231'));
Which will return 2016/01/02 - 1.
If you wish generate week number of a date, it will return the week number of the year(input date)
Thus, I think sql server treat '2015-12-31' as the last week of 2015.

Get the month and year now then count the number of rows that are older then 12 months in SQL/Classic ASP

I know this one is pretty easy but I've always had a nightmare when it comes to comparing dates in SQL please can someone help me out with this, thanks.
I need to get the month and year of now then compare it to a date stored in a DB.
Time Format in the DB:
2015-08-17 11:10:14.000
I need to compare the month and year with now and if its > 12 months old I will increment a count. I just need the number of rows where this argument is true.
I assume you have a datetime field.
You can use the DATEDIFF function, which takes the kind of "crossed boundaries", the start date and the end date.
Your boundary is the month because you are only interested in year and month, not days, so you can use the month macro.
Your start time is the value stored in the table's row.
Your end time is now. You can get system time selecting SYSDATETIME function.
So, assuming your table is called mtable and the datetime object is stored in its date field, you simply have to query:
SELECT COUNT(*) FROM mtable where DATEDIFF(month, mtable.date, (SELECT SYSDATETIME())) > 12