sql table 价格上涨
Price increase in sql table
我的table喜欢这样
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)
由于您的输入不会超过 1 步的增加,所以只需尝试 UNION
试试这个
SELECT * FROM
(
SELECT Date, F.Type, L.Price As Price From table
UNION ALL
SELECT Date, F.Type, F.Price As Price From table
UNION ALL
SELECT Date, F.Type, F.Price - L.Price As Price From table
)T ORDER BY Date,Price
如果您使用的是 MSSQL,则可以使用递归 CTE 尝试此解决方案-
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','apple',20,60,10
UNION ALL SELECT '05/11/2019','grape',50,100,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,2,3
我的table喜欢这样
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)
由于您的输入不会超过 1 步的增加,所以只需尝试 UNION
试试这个
SELECT * FROM
(
SELECT Date, F.Type, L.Price As Price From table
UNION ALL
SELECT Date, F.Type, F.Price As Price From table
UNION ALL
SELECT Date, F.Type, F.Price - L.Price As Price From table
)T ORDER BY Date,Price
如果您使用的是 MSSQL,则可以使用递归 CTE 尝试此解决方案-
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','apple',20,60,10
UNION ALL SELECT '05/11/2019','grape',50,100,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,2,3