i have 2 tables where from i'm trying to extract from table 1 the last 2 taxe dates per user who were taxed for the last time on the 19/06/2022 and with product id 12 in table 2, and the sum amount of taxes, as well as the time range between the two last taxe dates as mentionned in the image bellow .
WITH LAST_TWO AS (
SELECT *,ROW_NUMBER() OVER(PARTITION BY id ORDER BY tax_date DESC) AS time_ago
FROM table1
QUALIFY time_ago <= 2
),
AGG AS (
SELECT
id,
MIN(tax_date) as tax_date_MIN,
MAX(tax_date) as tax_date_MAX,
SUM(amount) as amount_SUM
FROM LAST_TWO
GROUP BY id
)
SELECT id, amount_SUM, DATEDIFF(day, tax_date_MIN, tax_date_MAX) as DATE_RANGE
FROM AGG
INNER JOIN table2 ON AGG.id = table2.id
WHERE table2.product_id = 12;
First step is to add a RANK() or ROW_NUMBER() to order the payments backwards, by id so you're only looking at the 2 last payments. Like this.
The next step is to aggregate those to get min and max dates, and sum of amount. Like this.
Lastly, you calculate the difference between min and max dates. Like this.
WITH LAST_TWO AS (
SELECT *,ROW_NUMBER() OVER(PARTITION BY id ORDER BY tax_date DESC) AS time_ago
FROM table1
QUALIFY time_ago <= 2
),
AGG AS (
SELECT
id,
MIN(tax_date) as tax_date_MIN,
MAX(tax_date) as tax_date_MAX,
SUM(amount) as amount_SUM
FROM LAST_TWO
GROUP BY id
)
SELECT id, amount_SUM, DATEDIFF(day, tax_date_MIN, tax_date_MAX) as DATE_RANGE
FROM AGG
INNER JOIN table2 ON AGG.id = table2.id
WHERE table2.product_id = 12;
发布评论
评论(1)
第一步是添加
等级()
或row_number()
以向后订购付款,id
,因此您只查看2个最后付款。喜欢 this 。下一步是汇总这些步骤以获取最小日期和最大日期以及金额之和。喜欢 this this this> this> this 。
最后,您计算最小日期和最大日期之间的差异。喜欢 this this this this>
First step is to add a
RANK()
orROW_NUMBER()
to order the payments backwards, byid
so you're only looking at the 2 last payments. Like this.The next step is to aggregate those to get min and max dates, and sum of amount. Like this.
Lastly, you calculate the difference between min and max dates. Like this.