sql表涨价

我的桌子是这样的

Date        F.Type  L.Price  H.Price  increase
04/11/2019  apple   10        30        10
04/11/2019  banana   2        6        2
05/11/2019  apple    20       60        20
05/11/2019  grape   50        100       25

我的要求

Date        F.Type    Price
04/11/2019  apple     10
04/11/2019  apple     20
04/11/2019  apple     30   (L.Price+increase upto H.Price)
04/11/2019  banana    2
04/11/2019  banana    4
04/11/2019  banana    6   (L.Price+increase upto H.Price)
05/11/2019  apple    20
05/11/2019  apple    40
05/11/2019  apple    60   (L.Price+increase upto H.Price)
05/11/2019  grape    50 
05/11/2019  grape    75 
05/11/2019  grape    100  (L.Price+increase upto H.Price)
yinghuochong512 回答:sql表涨价

如果您使用的是MSSQL,则可以使用递归CTE尝试此解决方案-

DEMO HERE

WITH your_table(Date,F_Type,L_Price,H_Price,increase)
AS
(
SELECT '04/11/2019','apple',50,100,10 
UNION ALL SELECT '04/11/2019','banana',2,6,2 
UNION ALL SELECT '05/11/2019',20,60,10 
UNION ALL SELECT '05/11/2019','grape',25
),CTE2 AS (
    SELECT 
    A.Date AD,A.F_Type FT,A.L_Price,A.L_Price inc,A.H_Price,A.increase
    FROM your_table A

    UNION ALL

    SELECT 
    B.AD,B.FT,B.L_Price,B.inc + B.increase increase,B.H_Price,B.increase
    FROM CTE2 B
    WHERE inc < B.H_Price
    AND AD = B.AD AND FT = B.FT
)

SELECT AD AS Date,FT AS F_Type,inc AS Price 
FROM CTE2
ORDER BY 1,3
,

输入的内容不会增加1步,所以只需尝试UNION

尝试一下

SELECT * FROM
(
    SELECT Date,F.Type,L.Price As Price From table
    UNION ALL
    SELECT Date,F.Price As Price From table
    UNION ALL
    SELECT Date,F.Price - L.Price As Price From table
)T ORDER BY Date,Price

DEMO

本文链接:https://www.f2er.com/3153210.html

大家都在问