| Product ID | YearBought | Sales | Min_Year | Max_Year |
| 1 | 2016 | $20 | 2011 | 2016 |
| 2 | 2016 | $10 | 2016 | 2018 |
| 2 | 2017 | $30 | 2016 | 2018 |
| 3 | 2017 | $5 | 2015 | 2019 |
| 3 | 2018 | $10 | 2015 | 2019 |
| 3 | 2018 | $20 | 2015 | 2019 |
| 3 | 2019 | $5 | 2015 | 2019 |
| 3 | 2019 | $30 | 2015 | 2019 |
| 4 | 2018 | $5 | 2018 | 2020 |
| 4 | 2019 | $10 | 2018 | 2020 |
| 4 | 2020 | $20 | 2018 | 2020 |
Min_Year = 产品首次推出的年份
Max_Year + 1 = 产品下架年份
上面是我正在使用的表格的示例。试图找到:
新产品首次推出当年带来的销售额总和
“销售额下降”的总和,即产品下降后一年的销售额总和(没有销售额)。(例如,产品在 2018 年带来了 15 美元,但在 2019 年没有销售额,希望在 2019 年销售额下降时显示 15 美元)
预期输出:
| YearBought | New Product Sales | Dropped Product Sales |
| 2016 | $10 | |
| 2017 | | $20 |
| 2018 | $5 | |
| 2019 | | |
| 2020 | | $35 |
正在考虑这样的事情,但它不起作用。任何帮助,将不胜感激!
select
YearBought,
sum(case when yearbought=min_year then sales else 0 end) as NewSales,
sum(case when yearbought=max_year+1 then sales else 0 end) as DropSales
from
#t
group by
yearbought