sql—通过从两个不同的行中减去基于多个ID的列值来创建自定义字段

jjhzyzn0  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(250)

我必须根据多个id从两个不同的行中减去列值来创建自定义列。
数据集如下:

------------------------------------------
Date       | Name | ID1  | ID2  | Value
------------------------------------------
2020-03-01 | ABC  | 50   | 75   | 2000
2020-03-02 | ABC  | 50   | 75   | 3000
2020-03-03 | ABC  | 50   | 75   | 3140
2020-03-01 | ABC  | 50   | 76   | 5000
2020-03-02 | ABC  | 50   | 76   | 6000
2020-03-03 | ABC  | 50   | 76   | 6145
2020-03-01 | ABC  | 50   | 77   | 5000
2020-03-02 | ABC  | 50   | 77   | 6000
2020-03-03 | ABC  | 50   | 77   | 6145

id2对于每个日期都是不同的。现在我必须显示自定义字段,如下所示:

---------------------------------------------------
Date       | Name | ID1  | ID2  | Value |  Custom 
--------------------------------------------------
2020-03-01 | ABC  | 50   | 75   | 2000  | 1000 (3000-2000)
2020-03-02 | ABC  | 50   | 75   | 3000  | 140  (3140 -3000)
2020-03-03 | ABC  | 50   | 75   | 3140  | Next date Value - 3140 
...

...

对其他id2也重复。
请建议我该怎么做。我试过用 Cross Join 但没有得到理想的结果。

fwzugrvs

fwzugrvs1#

试试这个:

DECLARE @DataSource TABLE
(
    [Date] DATE
   ,[Name] CHAR(3)
   ,[ID1] TINYINT
   ,[ID2] TINYINT
   ,[Value] INT
);

INSERT INTO @DataSource ([Date], [Name], [ID1], [ID2], [Value])
VALUES ('2020-03-01', 'ABC ', '50', '75', '2000')
      ,('2020-03-02', 'ABC ', '50', '75', '3000')
      ,('2020-03-03', 'ABC ', '50', '75', '3140')
      ,('2020-03-01', 'ABC ', '50', '76', '5000')
      ,('2020-03-02', 'ABC ', '50', '76', '6000')
      ,('2020-03-03', 'ABC ', '50', '76', '6145')
      ,('2020-03-01', 'ABC ', '50', '77', '5000')
      ,('2020-03-02', 'ABC ', '50', '77', '6000')
      ,('2020-03-03', 'ABC ', '50', '77', '6145');

SELECT *
     ,LEAD([Value]) OVER (PARTITION BY [Name], [ID1], [ID2] ORDER BY [Date] ASC)
     ,CONCAT(LEAD([Value]) OVER (PARTITION BY [Name], [ID1], [ID2] ORDER BY [Date] ASC) - [value], ' (', LEAD([Value]) OVER (PARTITION BY [Name], [ID1], [ID2] ORDER BY [Date] ASC), ' -', [value],')')
FROM @DataSource
ORDER BY [Date]

你可以在期末考试中加入更多的逻辑 CONCAT 以不同的方式塑造结果。例如,如果没有 next value 为了得到,你可以留下价值 NULL .

oyt4ldly

oyt4ldly2#

使用 lead() :

select t.*,
       (value - lead(value, 1, 0) over (partition by id1, id2 order by date)) as diff
from t;

相关问题