数据库
首页 > 数据库> > SQL每日一题(20220728)

SQL每日一题(20220728)

作者:互联网

参考:https://mp.weixin.qq.com/s?__biz=MzA3MTg4NjY4Mw==&mid=2457328780&idx=3&sn=2a8e460050381bdc794913173d315884&chksm=88a5ceb8bfd247ae589430ef72ff653c000e041829a8154a3ad27c7350b687bbfdcf0ad5bb96&scene=178&cur_album_id=1790847024611852294#rd

220728

题目

原始数据如下:

Carrier_Name OrderNumber ReSumCost
临时 JOY19080300003 170.00
张三 JOY19080300003 170.00
临时 JOY19080300004 196.50
张三 JOY19080300004 196.50
临时 JOY19080300006 458.80
张三 JOY19080300006 458.80
李四 JOY19080300007 272.00
李四 JOY19080300008 315.00
临时 JOY19080300008 315.00

相同OrderNumber只取一条ReSumCost的结果,希望得到:

Carrier_Name OrderNumber ReSumCost NewReSumCost
临时 JOY19080300003 170.00 170.00
张三 JOY19080300003 170.00 0.00
临时 JOY19080300004 196.50 196.50
张三 JOY19080300004 196.50 0.00
临时 JOY19080300006 458.80 458.80
张三 JOY19080300006 458.80 0.00
李四 JOY19080300007 272.00 272.00
李四 JOY19080300008 315.00 315.00
临时 JOY19080300008 315.00 0.00

数据脚本

CREATE TABLE F0728
(
    Carrier_Name NVARCHAR(10)   NOT NULL,
    OrderNumber  VARCHAR(20)    NOT NULL,
    ReSumCost    DECIMAL(10, 2) NOT NULL
);

INSERT INTO F0728 VALUES('临时', 'JOY19080300003', 170);
INSERT INTO F0728 VALUES('张三', 'JOY19080300003', 170);
INSERT INTO F0728 VALUES('临时', 'JOY19080300004', 196.5);
INSERT INTO F0728 VALUES('张三', 'JOY19080300004', 196.5);
INSERT INTO F0728 VALUES('临时', 'JOY19080300006', 458.8);
INSERT INTO F0728 VALUES('张三', 'JOY19080300006', 458.8);
INSERT INTO F0728 VALUES('李四', 'JOY19080300007', 272);
INSERT INTO F0728 VALUES('李四', 'JOY19080300008', 315);
INSERT INTO F0728 VALUES('临时', 'JOY19080300008', 315);

我的答案


参考答案

select *,
       IF(LAG(OrderNumber)
              over (partition by OrderNumber order by OrderNumber) = OrderNumber
           , 0, ReSumCost) NewReSumCost
from f0728;

标签:INSERT,20220728,OrderNumber,每日,张三,VALUES,SQL,INTO,F0728
来源: https://www.cnblogs.com/DJOSIMON/p/16540762.html