减少SQL Server中的查询冗余

时间:2018-01-04 07:27:19

标签: sql sql-server

SELECT
    invoiceNo AS Bill_No,
    SUM(ISNULL((OFI.[New Quantity] * OFI.[Unit Sell Price]),0)) AS Amount,
    SUM(ISNULL(((OFI.[New Quantity] * OFI.[Unit Sell Price]) + FBP.[Packing/Delivery Charges] + FBP.[Miscellaneous Charge]) * (FBP.[Additional Discount Percent] / 100), 0)) AS Discount 
FROM
    dbo.[Final Payment Bill] FBP
JOIN
    dbo.[Order] o ON o.finalPaymentBill_invoiceNo = FBP.invoiceNo
JOIN
    dbo.[Ordered Food Item] OFI ON o.[Order Number] = OFI.Order_orderNo
GROUP BY
    FBP.invoiceNo

从查询中可以看出,我必须两次编写相同的求和函数进行计算。还有其他办法让我不必再写一次吗?

PS:我不确定提出这个问题的正确方法。

3 个答案:

答案 0 :(得分:0)

重复是不大的。但是,您可以简化代码。 SUM()会忽略NULL个值,因此这可能符合您的要求:

select invoiceNo as Bill_No,
       sum(OFI.[New Quantity] * OFI.[Unit Sell Price]) as Amount,
       sum(OFI.[New Quantity] * OFI.[Unit Sell Price]) + FBP.[Packing/Delivery Charges] + FBP.[Miscellaneous Charge]) * (FBP.[Additional Discount Percent] / 100) as Discount 
from dbo.[Final Payment Bill] FBP join
     dbo.[Order] o
     on o.finalPaymentBill_invoiceNo = FBP.invoiceNo join
     dbo.[Ordered Food Item] OFI
     on o.[Order Number] = OFI.Order_orderNo
group by FBP.invoiceNo;

可以使用CTE或子查询(或在其他情况下,apply)避免重复。但在这种情况下,这似乎不值得努力。

更重要的问题是+不会忽略NULL值,因此,如果FPB列中的任何一列是NULL,那么该行的所有值都是忽略。

答案 1 :(得分:0)

我相信你可以使用子查询

select 
   invoiceNo as Bill_No,
   sum(FinalPrice) as Amount,
   sum(ISNULL((FinalPrice + FBP.[Packing/Delivery Charges] + FBP.[Miscellaneous Charge]) * (FBP.[Additional Discount Percent] / 100) ,0)) as Discount 
from dbo.[Final Payment Bill] FBP
join dbo.[Order] o
    on o.finalPaymentBill_invoiceNo = FBP.invoiceNo
join (select Order_orderNo, (OFI.[New Quantity] * OFI.[Unit Sell Price]) FinalPrice from dbo.[Ordered Food Item]) OFI
    on o.[Order Number] = OFI.Order_orderNo
group by FBP.invoiceNo

和CTE以提高可读性

with OFI as
(
   select Order_orderNo, (OFI.[New Quantity] * OFI.[Unit Sell Price]) FinalPrice 
   from dbo.[Ordered Food Item]
)
select 
   invoiceNo as Bill_No,
   sum(FinalPrice) as Amount,
   sum(ISNULL((FinalPrice + FBP.[Packing/Delivery Charges] + FBP.[Miscellaneous Charge]) * (FBP.[Additional Discount Percent] / 100) ,0)) as Discount 
from dbo.[Final Payment Bill] FBP
join dbo.[Order] o
    on o.finalPaymentBill_invoiceNo = FBP.invoiceNo
join OFI
    on o.[Order Number] = OFI.Order_orderNo
group by FBP.invoiceNo

答案 2 :(得分:0)

你在那里的重复没有问题。但是如果您在[Ordered Food Item]

上创建了一个计算列,则可以将其删除
ALTER TABLE [Ordered Food Item] 
ADD Amount 
AS ([New Quantity] * [Unit Sell Price])