我无法理解如何使用T-SQL查询解决此问题。 我有一个价格列和一个卷列。在另一张表中,a有不同音量水平的折扣。所以我的折扣表的值可以是
(StartLevel, DiscountFactor)
(0, 1);
(25, 0.95);
(50, 0.90);
(100, 0.75)
我想要的是计算总价。如果音量为35,我希望它乘以
Price x ((35-25) x 0.95 + (25-0) x 1)
如果音量为200,则应为
Price x ((200-100) x 0.75 + (100-50) x .9+(50-25) x .95+(25) x 1)
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:1)
这可以提供帮助:
DECLARE @products TABLE
(
id INT ,
price MONEY ,
volume INT
)
DECLARE @discounts TABLE
(
id INT ,
Level INT ,
Factor MONEY
)
INSERT INTO @products
VALUES ( 1, 10, 35 ),
( 2, 15, 200 )
INSERT INTO @discounts
VALUES ( 1, 0, 1 ),
( 2, 25, 0.95 ),
( 3, 50, 0.90 ),
( 4, 100, 0.75 )
SELECT p.id, p.price * SUM(ca.m)
FROM @products p
CROSS APPLY ( SELECT * ,
Factor * ( -Level + LEAD(Level) OVER ( PARTITION BY p.id ORDER BY Level, d ) ) AS m
FROM ( SELECT 1 AS d ,
Level ,
Factor
FROM @discounts
WHERE Level < p.volume
UNION ALL
SELECT 2 AS d ,
p.volume ,
0
) t
) ca
GROUP BY p.id
如果没有分组,则返回:
id price volume d Level Factor m
1 10.00 35 1 0 1.00 25.00
1 10.00 35 1 25 0.95 9.50
1 10.00 35 2 35 0.00 NULL
2 15.00 200 1 0 1.00 25.00
2 15.00 200 1 25 0.95 23.75
2 15.00 200 1 50 0.90 45.00
2 15.00 200 1 100 0.75 75.00
2 15.00 200 2 200 0.00 NULL
然后只有group by
产品和sum
的{{1}}会产生:
m
答案 1 :(得分:0)
对于给定的Volume
和Price
,您可以使用SQL Server 2012及更早版本中提供的LEAD
根据间隔获得折扣。
示例数据
DECLARE @PriceTable TABLE(Volume INT,Price DECIMAL(9,2) )
DECLARE @Discount TABLE(StartLevel int, DiscountFactor DECIMAL(9,2))
INSERT INTO @PriceTable
VALUES(75, 20.5),
(150, 20),
(250, 20.5),
(0, 15);
INSERT INTO @Discount
VALUES(0, 1),
(25, 0.95),
(50, 0.90),
(100, 0.75);
<强>查询强>
SELECT Volume,Price,FinalPrice
FROM @PriceTable P
CROSS APPLY(
SELECT SUM(CASE WHEN (MaxLevel >=StartLevel) THEN (MaxLevel-StartLevel) ELSE 0 END *DiscountFactor)*P.Price as FinalPrice
FROM
(
SELECT CASE WHEN LEAD(StartLevel)OVER(ORDER BY StartLevel) < P.Volume THEN LEAD(StartLevel)OVER(ORDER BY StartLevel) ELSE P.Volume END MaxLevel,StartLevel, DiscountFactor
FROM @Discount
) IQ
)T
<强>输出强>
Volume Price FinalPrice
75 20.50 1460.6250
150 20.00 2625.0000
250 20.50 4228.1250
0 15.00 0.0000