Snowflake how to obtain cumulative date values - date

Can someone help me with obtaining the result for below logic. I have a table with below columns.
TYPE SRC_CURR TAR_CURR EX_RATE EX_RATE_START_DATE
M GBP USD 1.36687 2/1/2021
M GBP USD 1.33636 1/1/2021
M GBP USD 1.32837 12/1/2020
M GBP USD 1.30242 11/1/2020
M GBP USD 1.27421 10/1/2020
M GBP USD 1.31527 9/1/2020
ZEU GBP USD 1.3654 1/20/2021
ZEU GBP USD 1.363 1/19/2021
ZEU GBP USD 1.3587 1/18/2021
ZEU GBP USD 1.359 1/15/2021
ZEU GBP USD 1.3689 1/14/2021
ZEU GBP USD 1.3639 1/13/2021
ZEU GBP USD 1.3664 1/12/2021
ZEU GBP USD 1.3518 1/11/2021
ZEU GBP USD 1.3568 1/8/2021
So I need to form a new column which is EX_RATE_END_DATE from above values as shown below. Ideally the requirement is to have EX_RATE_END_DATE to max 9999-12-31 by default for the latest start date and for rest of the records it should be previous max start date - 1.
Please find below the output required,
TYPE SRC_CURR TAR_CURR EX_RATE EX_RATE_START_DATE EX_RATE_END_DATE
M GBP USD 1.36687 2/1/2021 12/31/9999
M GBP USD 1.33636 1/1/2021 1/31/2021
M GBP USD 1.32837 12/1/2020 12/31/2020
M GBP USD 1.30242 11/1/2020 11/30/2020
M GBP USD 1.27421 10/1/2020 10/31/2020
M GBP USD 1.31527 9/1/2020 9/30/2020
ZEU GBP USD 1.3654 1/20/2021 12/31/9999
ZEU GBP USD 1.363 1/19/2021 1/19/2021
ZEU GBP USD 1.3587 1/18/2021 1/18/2021
ZEU GBP USD 1.359 1/15/2021 1/17/2021
ZEU GBP USD 1.3689 1/14/2021 1/14/2021
ZEU GBP USD 1.3639 1/13/2021 1/13/2021
ZEU GBP USD 1.3664 1/12/2021 1/12/2021
ZEU GBP USD 1.3518 1/11/2021 1/11/2021
ZEU GBP USD 1.3568 1/8/2021 1/10/2021
It would be great if someone help me with getting the desired result set by any possible ways in snowflake.

Could you please check below query:
select TYPE, SRC_CURR, TAR_CURR, EX_RATE, EX_RATE_START_DATE, CASE WHEN DATE_VALUE = 1 THEN '9999-12-31' ELSE LAST_DAY("EX_RATE_START_DATE", 'MONTH') END AS "LAST DAY OF YEAR" from ( SELECT TYPE, SRC_CURR, TAR_CURR, EX_RATE, EX_RATE_START_DATE, row_number() over(partition by type order by EX_RATE_START_DATE desc) as date_value FROM SOF_TEST1) a;

I have found the below logic to get the desired result. Please comment if this can be achieved in a better/other way.
select
TYPE,
SRC_CURR,
TAR_CURR,
EX_RATE,
EX_RATE_START_DATE ,
lag(EX_RATE_START_DATE) over ( PARTITION BY TYPE,SRC_CURR,TAR_CURR order by EX_RATE_START_DATE desc) as END_TEMP,
case when END_TEMP is NULL then '9999-12-31' else END_TEMP end as EX_RATE_END_DATE
from schema.target_table
order by TYPE,SRC_CURR,EX_RATE_START_DATE desc ;

Related

Count users with more than X amount of transactions within Y days by date

Scenario: Trying to count more active users for time series analysis.
Need: With postgreSQL(redshift) Count customers that have more than X unique transactions within Y days from said date, group by date.
How do i achieve this?
Table: orders
date
user_id
product_id
transaction_id
2022-01-01
001
003
001
2022-01-02
002
001
002
2022-03-01
003
001
003
2022-03-01
003
002
003
...
...
...
...
Outcome:
date
active_customers
2022-01-01
10
2022-01-02
12
2022-01-03
9
2022-01-04
13
You may be able to use the window functions LEAD() and LAG() here but this solution may also work for you.
WITH data AS
(
SELECT o.date
, o.user_id
, COUNT(o.trans_id) tcount
FROM orders o
WHERE o.date BETWEEN o.date - '30 DAYS'::INTERVAL AND o.date -- Y days from given date
GROUP BY o.date, o.user_id
), user_transaction_count AS
(
SELECT d.date
, COUNT(d.user_id) FILTER (WHERE d.tcount > 1) -- X number of transactions
OVER (PARTITION BY d.user_id) user_count
FROM data d
)
SELECT u.date
, SUM(u.user_count) active_customers
FROM user_transaction_count u
GROUP BY u.date
ORDER BY u.date
;
Here is a DBFiddle that demos a couple options.

Power BI DAX: Group by Monthly Growth Rate

I got the following sample data:
Product Group Product Monthly Start Date Sales Qty
Mobile Phone A Mobile Phone A-1 1/1/2021 100
Mobile Phone A Mobile Phone A-1 2/1/2021 120
Mobile Phone B Mobile Phone B-1 1/1/2021 90
Mobile Phone B Mobile Phone B-1 2/1/2021 78
What I want is to calculate the Monthly product growth rate (below).
Product Group Product Month Start Date Growth Rate
Mobile Phone A Mobile Phone A-1 1/1/2021 null
Mobile Phone A Mobile Phone A-1 2/1/2021 20%
Mobile Phone B Mobile Phone B-1 1/1/2021 null
Mobile Phone B Mobile Phone B-1 2/1/2021 -13%
I guess I need to use groupby and sort order by the Month Start Date and calculate the rate.
Does anyone know the best way of calculating it?
Thanks.
I would do it this way (assuming you are viewing the result with a monthly granularity):
Total Sales Qty = SUM( ExampleTable[Sales Qty] )
MTD Sales Qty =
TOTALMTD( [Total Sales Qty], Dates[Date] )
MTD Sales Qty LM =
CALCULATE( [MTD Sales Qty], DATEADD(Dates[Date], -1, MONTH ) )
MoM Sales Qty Change =
DIVIDE([MTD Sales Qty] - [MTD Sales Qty LM], [MTD Sales Qty LM], BLANK() )
You would calculate month-over-month growth using a sequence of four measures:
sum of the column
amount for the prior month
change month-over-month
change month-over-month %
These DAX patterns can can be used to get you started. Make sure you add the necessary columns to your date table, then modify the measures below with your date table, fact table column to be quantified and measures you create.
DAX Patterns - Month Related Calculations
Sum of the Fact Table Column
Sales Amount:= sum ( SalesTable[Sales Qty] )
Amount for Prior Month
Sales PM :=
VAR CurrentYearMonthNumber = SELECTEDVALUE ( 'Date'[Year Month Number] )
VAR PreviousYearMonthNumber = CurrentYearMonthNumber - 1
VAR Result =
CALCULATE (
[Sales Amount],
REMOVEFILTERS ( 'Date' ),
'Date'[Year Month Number] = PreviousYearMonthNumber
)
RETURN
Result
Change Month-Over-Month
Sales MOM :=
VAR ValueCurrentPeriod = [Sales Amount]
VAR ValuePreviousPeriod = [Sales PM]
VAR Result =
IF (
NOT ISBLANK ( ValueCurrentPeriod ) && NOT ISBLANK ( ValuePreviousPeriod ),
ValueCurrentPeriod - ValuePreviousPeriod
)
RETURN
Result
Change Month-Over-Month %
Sales MOM % :=
DIVIDE (
[Sales MOM],
[Sales PM]
)

How can I create a list of conversion rates and currency types from a table with converted values in BigQuery SQL?

I have a big table with many rows. A data example is the following:
Currency
Value
Value_in_NOK
USD
100
800
USD
200
1600
SEK
120
108
USD
400
3200
SEK
240
216
USD
300
2400
EUR
15
150
EUR
30
300
The converted value is always in NOK.
What I want is to use a SELECT statemnet to create a distinct list of Currencies, including the NOK, with the currency rate made from the first row with the distinct Currency:
Currency
Currency_Rate
USD
8.000
SEK
0.900
EUR
10.000
NOK
1.000
Assuming there is a some column in your table that defines order of rows - for example timestamp (ts)
select Currency, array_agg(round(Value_in_NOK/Value, 3) order by ts limit 1)[offset(0)] as Currency_Rate
from your_table
group by Currency
union all
select 'NOK', 1.000
if applied to sample data in your question - output is
This is the code I ended up with that works perfect.
SELECT
Opportunity_First_year_value_Currency,
ARRAY_AGG(ROUND(SAFE_CAST(Opportunity_First_year_value_converted AS NUMERIC)/SAFE_CAST(Opportunity_First_year_value AS NUMERIC), 5)
ORDER BY
Opportunity_Close_Date DESC
LIMIT
1) [
OFFSET
(0)] AS Currency_Rate
FROM
`JOINED_Opportunity`
WHERE
SAFE_CAST(Opportunity_First_year_value_converted AS NUMERIC) > 0
GROUP BY
Opportunity_First_year_value_Currency
UNION ALL
SELECT
'NOK',
1.00000

Getting complex cross sale details in PostgreSQL

I have an issue where i need to find out the details of the revenue that got from a cross sale product.
For example, I want to know which all are the category combinations a customer buy with a selected category.Also the amount spend by that customer on other categories other than the selected category.
Below is a sample Query which will give me the combinations and the revenue, Using a filter clause i can get the revenue of the category with and without the selected category if the combination count is 2 category, But when there more than 2 category in combinations i need to get the info how much each category cost, How can i get it?
Database : PostgreSQL Version 11
WITH filter_2 as
(
SELECT DISTINCT
o.order_number
, o.client_email
, COALESCE(category,'') AS category_name
, SUM(revenue) as revenue
FROM
orders o
INNER JOIN distinct_orders dos on dos.client_email=o.client_email
LEFT JOIN items i ON i.order_id = o.order_id
LEFT JOIN products p ON p.product_id = i.product_id
WHERE o.state ='Done'
GROUP BY o.order_number
, o.client_email, COALESCE(category,'')
)
,result_set_1 as
(
SELECT
f.order_number
,f.client_email
,string_agg(DISTINCT COALESCE(category,''), ' , ' ORDER BY COALESCE(category,'')) as cat_level_3_name
,COUNT(DISTINCT category) as prod_count
,SUM(revenue) revenue
FROM filter_2 f
GROUP BY f.order_number,f.client_email
)
SELECT
COUNT(DISTINCT order_number) as order_count,
COUNT(DISTINCT client_email) as customer_count
,category
,SUM(revenue) as revenue
FROM result_set_1 r
WHERE category IS NOT NULL
GROUP BY category
ORDER BY order_count DESC
Sample Input
Order_number client_email category Revenue
"819214" "olx#gmail.com" "A Tea" 290.00
"819214" "olx#gamil.com" "B Tea" 10.00
"608759" "lixxx#gmail.com" "A Tea" 15.00
"608759" "lixxx#yahoo.com" "B Tea" 20.00
"608759" "lixxx#gmail.com" "C Tea" 400.00
"237070" "news#gmail.com" "A Tea" 60.0
"237070" "news#gmail.com" "B Tea" 10.0
"508759" "chink#gmail.com" "A Tea" 15.00
"508759" "chink#gmail.com" "B Tea" 25.00
"508759" "chink#gmail.com" "C Tea" 45.00
"578759" "xxxx#gmail.com" "A Tea" 15.00
"588759" "xyyy#gmail.com" "A Tea" 15.00
"598759" "vtyy#gmail.com" "A Tea" 15.00
Expected Output
So if i want to know which all combination categories the customer bought up along with "A Tea",
Combinations Customer count Combination count Revenue Split UP
A Tea 7 3 ( Or 7) A Tee = 45 or (425)
A Tea, B Tea 2 2 A Tea = 350 B Tea = 20
A Tea, B Tea, C Tea 2 2 A Tea= 30 B Tea=45 C Tea = 445

API Paypal Payment Recurring

I have programmed a PaypalRequest Paypal where:
BILLINGPERIOD = Day
BILLINGFREQUENCY = 1
AMT = 10
TOTALBILLINGCYCLES = 3
Customer buys a reservation at a hotel, valued at USD 10.00, for 3 days
He will pay 10 USD each day until he completes 3 days.
How can I make it pay 3x 10 USD the same day?