简体   繁体   English

在 SQL 中动态聚合基于日期的列

[英]Aggregating a column based on date dynamically in SQL

This is more of a conceptual question.这更像是一个概念问题。 I'm trying to compare the sales that have happened this year with the last year.我试图将今年的销售额与去年的销售额进行比较。 But the comparison should be dynamic, as in, for this year I consider the sales that have happened till yesterday, and I need to consider the sales for the previous year till the same date last year as well.但是比较应该是动态的,例如,今年我考虑到昨天发生的销售额,我还需要考虑上一年到去年同一天的销售额。

For example, today is Dec 24th, so for 2021 I aggregate the sales till Dec 23rd, and I need to do the same for 2020 as well ie till Dec 23rd of 2020. And for tomorrow's report the aggregate should be till Dec 24th of 2021 and Dec 24th of 2020 respectively.例如,今天是 12 月 24 日,所以对于 2021 年,我将销售额汇总到 12 月 23 日,我也需要在 2020 年也这样做,即到 2020 年 12 月 23 日。对于明天的报告,汇总应该到 2021 年 12 月 24 日分别为 2020 年 12 月 24 日和 2020 年 12 月 24 日。

My code so far:到目前为止我的代码:

SELECT product_category,
       SUM(CASE WHEN purchase_date >= '2021-01-01' AND purchase_date < CURRENT_DATE THEN sales_revenue ELSE 0 END) AS revenue_2021,
       SUM(CASE WHEN purchase_date >= '2020-01-01' AND purchase_date < '2021-01-01' THEN sales_revenue ELSE 0 END) AS revenue_2020
FROM sales_table
GROUP BY 1
ORDER BY 1
       

Here, for 2021, my code works.在这里,2021 年,我的代码有效。 But for 2020 it would give the whole year (2020's) sum.但对于 2020 年,它将给出全年(2020 年)的总和。 Is there anyway I can make this dynamic for 2020 just the same way it happens for 2021?无论如何,我是否可以像 2021 年一样让 2020 年充满活力?

SELECT product_category,
       SUM(CASE WHEN purchase_date >= DATEADD(yy, DATEDIFF(yy, 0, CURRENT_DATE), 0)

 AND purchase_date < CURRENT_DATE THEN sales_revenue ELSE 0 END) AS revenue_2021,
       SUM(CASE WHEN purchase_date >= DATEADD(yy, DATEDIFF(yy, 0, CURRENT_DATE)-1, 0) AND purchase_date < dateadd(yy, -1, CURRENT_DATE) THEN sales_revenue ELSE 0 END) AS revenue_2020
FROM sales_table
WHERE
purchase_date >= DATEADD(yy, DATEDIFF(yy, 0, CURRENT_DATE)-1, 0)
GROUP BY 1
ORDER BY 1
      

I figured this out by myself and this seems to work.我自己解决了这个问题,这似乎有效。

SELECT EXTRACT(YEAR FROM DATE_TRUNC('YEAR',purchase_date) AS Year,
product_category,
SUM(sales_revenue)
FROM sales_table
WHERE DATE_PART('MONTH',purchase_date)*100 + DATE_PART('DAY',purchase_date_time)
< DATE_PART('MONTH',CURRENT_DATE)*100 + DATE_PART('DAY',CURRENT_DATE)
GROUP BY 1,2
ORDER BY 1,2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM