SQL避免在子查询上使用多部分标识符

时间:2019-06-17 08:18:54

标签: sql sql-server-express

使用SQLExpress 2017

我在仓库中分发了一些产品,我想看看需要多少库存才能满足给定时期的销售额。

Need pr. warehouse = Stock - CustomerOrders + SupplierOrders - SumOfSalesInPeriod

现在,我想对每种产品进行总结,但是我对已经满足需求的仓库不感兴趣,所以我只想要负值,但是在遇到问题时很难使它起作用多部分标识符错误。 使用distinct关键字也使我认为我进行了太多的计算,因此必须有一种更好的方法。

declare @fromDate date = '1900-01-01 12:00:00';
declare @toDate date = '3000-01-01 12:00:00';

select *,
    balance =  
        (select 
            turn = sum(TurnOver)
        from (
        select 
            WarehouseStocks.Id,
            TurnOver = WarehouseStocks.Qty 
                        - WarehouseStocks.OrderedByCustomersQty 
                        + WarehouseStocks.OrderedFromSuppliersQty 
                        - isnull((select Sum(StockEntries.Qty) 
                                    from StockEntries 
                                    where 
                                        StockEntries.Type = 1 
                                        and StockEntries.ProductId = WarehouseStocks.Id 
                                        and WarehouseStocks.WarehouseId = StockEntries.WarehouseId 
                                        and StockEntries.Date >= @fromDate 
                                        and StockEntries.Date <= @toDate), 0) 
        from WarehouseStocks) Product where TurnOver < 0
        group by Product.Id) tp where Products.Id = tp.Id)
from Products

1 个答案:

答案 0 :(得分:1)

我将改用CTE重写此代码,以分解它并使查询更具可读性。像这样:


declare @fromDate date = '1900-01-01 12:00:00';
declare @toDate date = '3000-01-01 12:00:00';

;with SE 
as
(
    select Sum(StockEntries.Qty) as SumStockEnties , StockEntries.ProductId, StockEntries.WarehouseId 
    from StockEntries 
    where 
        StockEntries.Type = 1 
        and StockEntries.Date >= @fromDate 
        and StockEntries.Date <= @toDate
    group by StockEntries.ProductId, StockEntries.WarehouseId 
),
TP
as
(
    Select WS.Id, WS.Qty - WS.OrderedByCustomersQty + WS.OrderedFromSuppliersQty - isnulle(SE.SumStockEnties, 0) as TurnOver
    from WarehouseStocks as WS
         left join SE
         on  SE.ProductId = WS.Id
          and SE.WarehouseId = WS.WarehouseId 
)
Select *
from TP 
    inner join Products as PR
    on PR.id = TP.id
Where PR.TurnOver < 0