Snowflake Extracting Month, year from date - snowflake-cloud-data-platform

I have a table with a column called created_date that has date like 2020-01-01 00:00:00.000
and I'm trying to create a column that will show only the year, another one the month
and one that shows the month as a string
here what I try
select date_part(year,'created_date ') as year,
date_part(month, 'created_date ') as month
to_char(Month, 'created_date') as month_name,
user_name,
product
from user_table
Unfortunately when running the query above, I get an error that Function Extract do not support VARCHAR(10) argument type
The result I'm trying to get is to who a table like
year month month_name user_name product
2021 01 January John Doe Ninja Mixer
2021 05 May Clide Smith Blender
Any help will be appreciated as I'm mostly used to MS sql and we just switch to snowflake.

Assuming the "created_date" is stored as a timestamp or datetime (synonyms), then you just need to remove the single quotes from around the created_date column name and change "to_char" to use the "monthname" function:
select date_part(year, created_date) as year,
date_part(month, created_date) as month,
monthname(created_date) as month_name,
user_name,
product
from user_table

Related

How to convert a date column in TSQL to display only the month and year

I have a column called DateId that is an int, and displays the date as 20190626. I was able to convert it to a date using the below query, but I would like to display it only as Month and Year.
I have three columns DateId, Customer and PayAmount, all from the same table. There are Many customers who have multiple payments each month and I would like to group by each month combining all the payments each month per customer.
Select
Convert(Date, Convert(Char(8), DateId), 112) As [Date],
Sum(PayAmount), Customer
from
Pay
Group By
Customer, DateId
What I get:
DateId PayAmount Customer
--------------------------------------
2019-06-20 $100 A
2019-06-24 $200 B
2019-04-22 $100 B
2019-03-20 $300 A
2019-04-22 $100 B
2019-06-21 $200 A
2019-06-21 $100 B
What I want:
DateId PayAmount Customer
-------------------------------------
2019-06 $300 A
2019-06 $300 B
2019-04 $200 B
2019-03 $300 A
Another option is to use the implicit conversion. In this case, LEFT(DateID,7).
Example Updated for INT
Select DateID = stuff(left(DateID,6),5,0,'-')
,[PayAmount] = sum([PayAmount])
,Customer
From YourTable
Group By left(DateID,6),Customer
Returns
DateID PayAmount Customer
2019-03 300 A
2019-06 300 A
2019-04 200 B
2019-06 300 B
This seems like you just need the first 7 characters of the ISO8601 style:
CONVERT(varchar(7),DateId,126)
If you want to retain the date datatype, then you'll need to "round" the date to the start of the month. One common way of doing this is the below method of getting the difference in months between the value and date "0" (1900-01-01):
CONVERT(date,DATEADD(MONTH,DATEDIFF(MONTH, 0, DateId),0))
If you then need to show the format yyyy-MM you can set that as your format in your presentation layer.
If you need to group by that as well, then add that expression to your GROUP BY clause.

Get customers age in months from a given column (SQL Server 2017)

I am new to SQL just wanted to know if I have one row with date of birth of few customers and I have to create a new column while creating a view with the customer_id and customer age in month as of today(Age_in_months = Current date - Date of birth of customer). How do I do it ?
I have tried date diff , some suggested to use floor and cast but I keep getting errors
One of them
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value '01-05-1974' to data type int.
Can somebody please suggest a very simple solution to this?
Thank you!
Thanks you as I see your query works fine went data is inserted manually . I imported the CSV file so this created a string type entry in sql . Your query gave me the same error I just had to fix it with convert
select customer_Id ,
DOB, DATEDIFF(month, CONVERT(date, Customer.DOB, 103), GETDATE()) as
[Age In Months] from Customer;
Since you haven't provided the Table or Column names I will assume the Table is Customers and the columns are id and dob.
Here is some example SQL to get the information
select
id as [Customer ID],
dob as [Date Of Birth],
datediff(month, cast(dob AS DATE), getdate()) as [Age In Months]
from
customers
First, we will take the Date Of Birth and make sure it is a date and not a Varchar or int, then we wrap that in a DATEDIFF to get the difference between the date in the dob column and the current date in months.
And this is the output
Customer ID Date Of Birth Age In Months
----------- ----------------- -------------
1 01-01-1991 331
2 01-01-2018 7

Is there a way to create a date column from other columns?

As the title says, can I create a new column from two fields? For example, I created a new column from the master values table to represent the months, and I have another column with the year. Can I combine them to create a date with whatever day? What I have is on the left, what I want is on the right:
Month Year NewDate
---- ---- -------
3 2015 2015-03-01
4 2015 2015-04-01
Whenever I tried to cast the month as datetime, it would look like this:
1900-01-03
This is probably a dumb question, but I created a timeline that lists out the months, and the trouble lies whenever the end date parameter chosen is less than the start date parameter, such as December 2015 to January 2016. I created the report in SSRS and the parameters aren't quite working correctly. Thanks guys!
Also, here's a snapshot of what the timeline looks like:
SELECT
DATEFROMPARTS ( [Year], [Month], 1 ) AS NewDate
FROM
YourTable
;
select dateadd(mm, t.Month -1, dateadd(yy,t.Year-1900,'19000101'))
from table1 t

Calculate payments on a month by month bases from date opened SQL 2008

I'm currently trying to replicate an old report that used to produce a rolling sum of collections. However it wasn't a standard month on month. Here is screen shot of the excel based report.
The blue section is based on a simple query and gives the dataset used to start(EXAMPLE):
SELECT COUNT(AccountNo) AS Number, SUM(Balance) AS Value, DATENAME(MM,DateOpened) AS Month, DATEPART(Y,DateOpened) AS Year FROM tblAccounts
GROUP BY DATENAME(MM,DateOpened), DATEPART(Y,DateOpened)
The tables are very basic :
AccountNo | Balance | DateOpened
12345 | 1245.55 | 01/01/2015
I'm struggling to get it to work out the months on a rolling basis, so Month 1 for Apr 2011 will be the first month for those files (payments in April), month 2 would be payments in May for the accounts opened in April (I hope that is clear).
So this means Month 1 for April would be April, and Month 1 for Nov would be Nov. Payments are stored in a table tblPayments
AccountNo | DatePayment | PaymentValue
12345 | 02/02/2015 | 15.99
Please ask if I haven't been clear enough
Assuming you have a column called "DatePayment", you should simply do something like this:
SELECT COUNT(AccountNo) AS Number, SUM(Balance) AS Value,
DATENAME(MM,DateOpened) AS Month, DATEPART(Y,DateOpened) AS Year,
DATEDIFF(MONTH, DateOpened, DatePayment) AS MonthN
FROM [...]
GROUP BY DATENAME(MM,DateOpened), DATEPART(Y,DateOpened),
DATEDIFF(MONTH, DateOpened, DatePayment)
The DATEDIFF simply counts the months between the date the account was opened and the date of the payment. Note that you might want to change the DateOpened to always be the 1st of the month in the DATEDIFF calculation.
In the FROM [...] part of your query, you will need a join between your Payments-table and the table holding your accounts, in order to be able to compare DateOpened with DatePayment. You should join them on the AccountNo-column. This looks something like this:
FROM Accounts INNER JOIN Payments ON Accounts.AccountNo = Payments.AccountNo
After doing this, you will need to make sure that all references to columns that exist in both tables are fully qualified. This means that COUNT(AccountNo) should be changed to COUNT(Accounts.AccountNo), etc.

Return all month names in chronological order instead of alphabetical

I have a date field (e.g log date of a ticket), which has all the ticket created dates. I want to display all the month names in order (i.e. January, February, March...)
The log date format is 2011-08-09 10:13:000. I can use DateName(Month,(Log_Date)) which will give the name of the month.
When I use the query
SELECT DISTINCT DateName(Month,(Log_Date)) FROM TABLE_NAME
ORDER BY DateName(Month(Log_Date))
It shows April, August, ... but I want to display January, February, March, ...
Order By
SELECT DISTINCT Datename(month,(Log_Date)), month(Log_Date)
FROM TABLE_NAME
ORDER BY month(Log_Date)
So you are ordering by the month's numerical representation, not the name.
OR Alternatively selecting only the month's name:
CREATE TABLE #tempMonth
(
id INT,
name VARCHAR(100)
)
INSERT INTO #tempMonth
SELECT DISTINCT month(ACT_CustSince) as id, DATENAME(month, ACT_CustSince) as name
FROM tblAccounts
ORDER BY month(ACT_CustSince)
SELECT name
FROM #tempMonth
DROP table #tempMonth

Resources