Java教程

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;
这篇关于SQL每日一题(20220728)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!