我有订单表和价目表。如果在价格细分表中存在项目代码,则根据数量降低价格。对于这样的条件,我不确定语法是什么,所以我将寻求帮助。这是一个示例DDL和一个我从case语句开始的查询,但不确定如何完成它。
DECLARE @Parent TABLE
(
itemname VARCHAR(100),
itemprice FLOAT,
itemqty INT
)
DECLARE @Exceptions TABLE
(
itemname VARCHAR(100),
qtyordered VARCHAR(10),
itemrpice FLOAT
)
INSERT INTO @Parent ( itemname, itemprice, itemqty )
VALUES ( 'rr11', 0.00 , 10 ),
( 'rr11', 0.00 , 5 ),
( 'rr11', 0.00 , 22 ),
( 'mc22', 15.00, 5 )
INSERT INTO @Exceptions ( itemname, qtyordered, itemrpice )
VALUES ( 'rr11', '1-5' , 15.50 ),
( 'rr11', '6-10', 11.00 ),
( 'rr11', '>11' , 17.00 )
Select
itemname
,case when itemprice IN (Select itemrpice from @Exceptions) Then
--compare the quantities to gather the pricing info
itemqty
FROM @Parent发布于 2017-04-06 19:46:14
您应该将订购的数量分解为两列或至少一个整数列(但我喜欢两列)。MinQuantity和MaxQuantity.注意,我通常不允许在表或列中使用缩略语,但是如果它被普遍接受,比如Min和Max,我会做例外。其次,适当地命名您的表,在我看来,像PriceBreak这样的东西比异常更具有描述性(这可能意味着任何事情)。
一旦我们有了正确的表名、列名和数据类型,解决方案就变得容易多了。您将使用itemname和itemquantity连接到正确的行( minquantity和maxquantity之间的itemquantity)。很好地命名一切是一个好主意,原因之一是代码变得自我文档化,更容易创建和排除故障。在这种情况下,您甚至不需要一个case语句,只需要一个左联接和一个ISNULL。
DECLARE @Order TABLE
(
itemname varchar(100)
,itemprice money
,QuantityOrdered int
)
DECLARE @PriceBreak TABLE
(
itemname varchar(100)
,MinQuantity int
,MaxQuantity int
,itemprice money
)
INSERT INTO @Order (itemname, itemprice, QuantityOrdered)
VALUES
('rr11', '0.00', 10)
,('rr11', '0.00', 5)
,('rr11', '0.00', 22)
,('mc22', '15.00', 5)
INSERT INTO @PriceBreak (itemname, MinQuantity, MaxQuantity, itemprice)
VALUES
('rr11', 1,5, '15.50')
,('rr11', 6,10, '11.00')
,('rr11', 11,99999, '17.00')
SELECT
O.itemname
,ISNULL(PB.ItemPrice, O.itemprice) ItemPrice
,QuantityOrdered
,ISNULL(PB.ItemPrice, O.itemprice) * QuantityOrdered
FROM
@Order O
LEFT JOIN @PriceBreak PB ON O.itemname = PB.itemname AND O.QuantityOrdered BETWEEN PB.MinQuantity and PB.MaxQuantityhttps://dba.stackexchange.com/questions/169362
复制相似问题