用于获取股票数据的SQL查询

时间:2013-12-15 18:46:25

标签: sql sql-server-2008 linq-to-sql

我正在进行查询,以获取特定日期范围内的销售和购买数据的库存明细(销售,购买,退货)。

但是这个查询在返回时不会返回任何数据。

这是有问题的查询:

select 
    pro.Name 'ItemName',
    (select (ISNULL(SUM(SPurchases.Qty),0)-ISNULL(SUM(SOrder_return.Qty),0))-(ISNULL(SUM(SSales.Qty),0)- ISNULL(SUM(SSales_returns.Qty),0)) 
from
    [Order] _SOrder
left outer join 
    Order_Item SPurchases on _SOrder.Id = SPurchases.[Order] 
                          and SPurchases.OrderType = 1 and SPurchases.Product = pro.Id
left outer join 
    Order_Item SOrder_return on _SOrder.Id = SOrder_return.[Order] 
                             and SOrder_return.OrderType = 2 and SOrder_return.Product = pro.Id
        ,Sale _SSale  
left outer join 
    Sale_Item SSales on _SSale.Id = SSales.Sale and SSales.SaleType = 1 
                     and SSales.Product = pro.Id
left outer join 
    Sale_Item SSales_returns on _SSale.Id = SSales_returns.Sale 
                             and SSales_returns.SaleType = 3 and SSales_returns.Product = pro.Id
where 
    _SOrder.Date<@StartDate
    and _SSale.Date<@StartDate) as 'Opening',   
   isnull(SUM(purchases.Qty),0) as 'Purchase',
   isnull(SUM(order_return.Qty),0) as 'PurRet',
   isnull(SUM(sales.Qty),0) as 'Sale',
   isnull(SUM(sales_returns.Qty),0) as 'SaleRet'
from 
   Product pro, [Order] _Order
left outer join 
   Order_Item purchases on _Order.Id = purchases.[Order] and purchases.OrderType = 1 
left outer join 
   Order_Item order_return on _Order.Id = order_return.[Order] and order_return.OrderType = 2 
    ,Sale _sale
left outer join 
   Sale_Item sales on _sale.Id = sales.Sale and sales.SaleType = 1 
left outer join 
   Sale_Item sales_returns on _sale.Id = sales_returns.Sale and sales_returns.SaleType = 3 
where 
   _Order.Date >= @StartDate and _Order.Date <= @EndDate
   and _sale.Date >= @StartDate and _sale.Date <= @EndDate
   and purchases.Product = pro.Id 
   and order_return.Product = pro.Id 
   and sales.Product = pro.Id 
   and sales_returns.Product = pro.Id 
group by 
   pro.Name, pro.Id
如果您需要有关架构和数据的更多信息,请

I have uploaded the the complete schema with data到SqlFiddle。

1 个答案:

答案 0 :(得分:0)

where子句

中有很多项
and purchases.Product=pro.Id and order_return.Product=pro.Id and sales.Product=pro.Id and sales_returns.Product=pro.Id 

只有在外部联接中的所有项目都存在时才能为真。鉴于你选择做一个外连接,我会假设它们是可选的,因此并不总是存在。

不要将它们放在where中,而是将它们放在join语句中:

left outer join Sale_Item sales_returns on 
                    on _sale.Id=sales_returns.Sale 
                       and sales_returns.SaleType=3 
                       and sales_returns.Product=pro.Id