在sql语句中使用if或case和multiple

taor4pac  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(360)

我想做这样的事
这很管用 Select ID, number, cost from table order by number 数字可以是2-x倍,但成本和

1 A33  66.50

2 A34  73.50

3 A34  73.50

但是我想要

1 A33  66.50

2 A34  73.50

3 A34  0

我想在sql中将其更改为0,我尝试了distinct或if then else。
我想做这样的事

declare @oldcost int;

 Select ID, number, 
    if(cost=@oldcost) then
       cost=0;
    else
       cost=cost;
    end if
    @oldcost=cost;

from table order by number

如何在sql中实现它?

i5desfxk

i5desfxk1#

可以使用窗口函数和 case 表达式:

select ID, number,
       (case when row_number() over (partition by number order by id) = 1
             then cost else 0
        end) as cost
from table
order by number, id;

请注意,sql通常不考虑排序,因此结果可以按任何顺序返回,甚至可以使用 order by ,具有相同键的行可以是任意顺序(并且在不同的执行上可以是不同的顺序)。
因此 order by 包括 id 以及 number 所以你得到了 cost 在“第一”行 number.

相关问题