根据列的值使用SQL求和

根据列的值使用SQL求和,sql,tsql,Sql,Tsql,我有3列:年、价格和日类型 我只想保留day_type=1或2的行,但在day_type=0时将值添加到这些行中 预期结果: year day_type price 2016 1 30 2016 2 15 2017 1 20 2017 2 17 我如何才能做到这一点?您可以使用连接: 如果其中一年的价格不为0,则使用左连接。这里是使用union all的另一种方法 具有总和窗口功能: select * from ( select year, (2 * day_type) % 3 as da

我有3列:年、价格和日类型

我只想保留day_type=1或2的行,但在day_type=0时将值添加到这些行中

预期结果:

year day_type price
2016 1 30
2016 2 15
2017 1 20
2017 2 17
我如何才能做到这一点?

您可以使用连接:


如果其中一年的价格不为0,则使用左连接。

这里是使用union all的另一种方法

具有总和窗口功能:

select * from (
  select year, (2 * day_type) % 3 as day_type,
  sum(price) over (partition by year) - price as price
  from tablename 
) t
where day_type <> 0
order by year, day_type

@斯盖德斯。非常感谢。
select t.year, t.day_type, (t.price + coalesce(t0.price, 0)) as price
from t left join
     t t0
     on t.year = t0.year and t0.day_type = 0
where t.day_type <> 0;
select year, max(day_type) day_type, sum(price) price 
from (
select 'A' dummy_col,* from tablename where day_type <>2
union all
select 'B' dummy_col,* from tablename where day_type <>1) t
group by dummy_col, year;
select * from (
  select year, (2 * day_type) % 3 as day_type,
  sum(price) over (partition by year) - price as price
  from tablename 
) t
where day_type <> 0
order by year, day_type
year | day_type | price
---: | -------: | ----:
2016 |        1 |    30
2016 |        2 |    15
2017 |        1 |    20
2017 |        2 |    17