How to get a weekly view from date field in snowflake - snowflake-cloud-data-platform

I have a small query mentioned below.
Need to break down a date field "DAY" to monthly and weekly wise in snowflake.
Input:
DAY
-------
2022-06-09
2022-04-04
Output
DAY_MONTH
----------
2022-06-01
2022-04-01 Monthly wise--- Its done
Here I have used
DATE_FROM_PARTS( YEAR(DAY), MONTH(DAY), 1) AS DAY_MONTH
DAY_WEEK
----------
2022-06-06
2022-04-04
They should be first day of working days like (Monday). How to do that for a weekly view?

I think you're looking for the date_trunc function:
set ts = '2022-07-07 11:14:00'::timestamp;
select date_trunc('DAY', $TS);
select date_trunc('WEEK', $TS);
select date_trunc('MONTH', $TS);
This is showing for a timestamp to show how it truncates to the day, but it works the same way for date types. Truncating to the week will start by the week_start parameter that's in effect (it will default to Monday as the start for this function):
https://docs.snowflake.com/en/sql-reference/parameters.html

Related

Snowflake Extracting Month, year from date

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

How to convert string to date format when string has only two digits for a year (Oracle, Netezza)

I have this issue databases: on Oracle and Netezza.
ISSUE: I have a string: 16101211213. This string means: YYMMDDHH24MMSS. I need to convert it to date format YYYY-MM-DD HH24:MM:SS. So on the way I need to add the two digits (in front of the string). I know that dates are for XXI century. So I need to 20 at the begining.So in result I should get 2016-10-12 21:12:13
Can anybody help me with it? I have tried many options (mainly on Netezza) but could not figure it out.
Thanks a lot in advance!
RR might be your savior.
SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';
Session altered.
SQL> with test as (select '16101211213' datum from dual)
2 select to_date(datum, 'rrmmddhh24miss') result
3 from test;
RESULT
-------------------
12.10.2016 11:21:03
SQL>
Oh, and - be careful! You used wrong format mask for minutes; it is "MI", not "MM" (which is a month).
[EDIT: displaying result using a different format mask]
SQL> with test as (select '16101211213' datum from dual)
2 select
3 to_date(datum, 'rrmmddhh24miss') result_1,
4 to_char(to_date(datum, 'rrmmddhh24miss'), 'mm/dd/yyyy hh:mi:ss am') result_2
5 from test;
RESULT_1 RESULT_2
------------------- ----------------------
12.10.2016 11:21:03 10/12/2016 11:21:03 AM
SQL>
You can either reply on Oracle inferring the year by converting with the YY or RR format model elements, or concatenate the century value and use YYYY.
If you are really sure that the dates are all in the 21st century then using concatenation and YYYY:
to_date('20' || tistamp, 'yyyymmddhh24miss')
will behave the same as using YY (which uses the current date to decide the century):
to_date(tistamp, 'yymmddhh24miss')
and if all the years are below 50 then RR (which uses the current date's century or the last century depending on the supplied 2-digit year) will also get the same result:
to_date(tistamp, 'rrmmddhh24miss')
But if any of the values are 50 or above RR and YY/YYYY behave differently. As these seem to be event timestamps it's unlikely they will be in the future, but the difference may still matter one day. (But then, eventually, assuming 21st century might not be valid either...)
Quick demo of the difference, using your sample value and a couple of others, supplied via a CTE:
alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS';
with your_table(tistamp) as (
select '16101211213' from dual
union all select '491231235959' from dual
union all select '500101000000' from dual
)
select to_date('20' || tistamp, 'yyyymmddhh24miss') as yyyy,
to_date(tistamp, 'yymmddhh24miss') as yy,
to_date(tistamp, 'rrmmddhh24miss') as rr
from your_table;
YYYY YY RR
------------------- ------------------- -------------------
2016-10-12 11:21:03 2016-10-12 11:21:03 2016-10-12 11:21:03
2049-12-31 23:59:59 2049-12-31 23:59:59 2049-12-31 23:59:59
2050-01-01 00:00:00 2050-01-01 00:00:00 1950-01-01 00:00:00
All of these would also work with to_timestamp() of course; as you don't have fractional seconds or time zone info using dates should be fine as long as your client knows that Oracle dates have a time component.

how to skip a day to previous in sql database if that day produce no files

i need to print the files From the current day plus from the day before...but if the day before is sunday then i want to print the files from saturday
i have a database containing a files of a month..each day produces some files but sunday is a holiday and at that day no files are generated.now i have done the query to pick the files in such a way that giving current date will results the files of that day and previous day. But the problem is on monday when i give the current date it produces files of monday and sunday... i dont want to print files of sunday as it is null,instead of that when am giving the current date if its is monday i should get the files of saturday instead of monday.
this is the code am using now
select files from table1 where [date]>=DATEADD(DAY,DATEDIFF(DAY,0,GETDATE()-1),0) ";
except for sundays i have entered the files for each day
insert into dbtable(date,files) values('date value',' filename');
Assuming your are using SQL Server (and not MySQL), you can use a CROSS APPLY to get data for the last two [dates] with files:
SELECT *
FROM dbo.table1 o
CROSS APPLY ( SELECT TOP 2 [date]
FROM dbo.table1 i
GROUP BY [date]
WHERE [date]>=DATEADD(DAY,DATEDIFF(DAY,0,GETDATE()-5),0)
ORDER BY [date] DESC
) det
WHERE det.[date] = o.[date]
Look for both dates, the current and the one before. From these records take the newer one.
select files
from table1
where date =
(
select max(date)
from table1
where date in (getdate(), getdate() - interval 1 day)
);
(Updated regarding Code-Monk's commment. Thanks.)
This is standard SQL except for the date manipulation which is MySQL specific. If you were mistaken with the DBMS tagged, then replace the part where a day is subtracted from current day with what's appropriate for your DBMS.)
UPDATE: You want to select from two days, the currect day and the last date before. As there should be no future records, this always means the two maximum dates in your table.
The slightly altered query using ORDER BY and LIMIT:
select files
from table1
where date in
(
select date
from table1
order by date desc limit 2
);
Try MySQL function DAYNAME(date1) to check for day is sunday,If so then get difference of two days instead of one.
mysql> SELECT DAYNAME(GETDATE());
+-----------------------+
| DAYNAME('2008-05-15') |
+-----------------------+
| Thursday |
+-----------------------+
1 row in set (0.01 sec)
If you are using SQL server,you can try datename function to get the day name:
datename(dw,getdate())
Try this for SQL Server:
SELECT files from table1
where [date]>=DATEADD(DAY,case when datename(dw,(GETDATE()-1))='SUNDAY' THEN -2 ELSE -1 END,getdate());
For MySQL Server Try:
SELECT files from table1
where `date`>=DATE_SUB(current_Date,interval (case when DAYNAME(date_sub(current_date,interval 1 day))='SUNDAY' THEN 2 ELSE 1 END) day);
Hope this works, because I don't have mysql here to test (only SQL Server):
SELECT files FROM table1
WHERE CAST([date] AS DATE) IN (CURDATE() - CASE DATEPART(dw,GETDATE()) WHEN 2 /* Monday */ THEN 2 ELSE 1 END, CURDATE())
The idea is to test if the date (as date only, no time part) falls in a specific list of dates, being today and yesterday or Saturday.

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.

SQL Query for SSRS report

I would like to create an ssrs report as below --
I have the following columns to be displayed-
| Tickets | Tickets |
| scanned on| scanned on|
Attraction | Hour | 09/08/2014| 09/09/2014| 09/10/2014| Day 4| Day 5| Day 6| 09/14/2014
Monday Tuesday Wednesday ...................... Sunday
U Mueseum | 9:00 AM | 10 | 40 |
10:00 aM |
..
..
..
..
..
23:00 AM
I will get the Start Date and End Date from the user. Now my problem is that I want a query for 7 days starting from the Start Date selected by the user to the End Date and for each hour i.e. for 1 day it would be 24 hrs, so 24*7 hours in total. When I display the value for scans in my current sql query it displays just for one day. How can I do it for 7 days, and the value of scans for that date should be displayed in the respective week day ie. Monday or Tuesday and so on. I am not able to get as to for each date and each hour the scan value changes, so I am confused and mixing up all here. The values for each hour on each day should be different and there is only one scan column, so how will the distinct values show up in the table.
I used the pivot table to convert the name of the week day from rows to individual columns.
Then the problem arises for ssrs report. How can this be executed in an ssrs report where the rows are for each hour and the columns displays the dates of the week selected. How can I achieve that in ssrs? I am getting currently for only 24 hrs, but i want the report to run for all 24 hrs for 7 days and should display the value side by side for each hour in each week day column.
Thank you.
Pass in one parameter into your stored procedure called #StartDate.
In SQL create the #EndDate like this
DECLARE #EndDate DATETIME
SET #EndDate = DATEADD("d",7,#StartDate)
Return your date information in an hour and a day column. Then use the grouping feature in ssrs to display the data.
I hope this helps you get a bit further with your issue.
Bobby
You could do this pretty easily with a Date Dimension table and a PIVOT operator. Give that a try.

Resources