我正在編寫一些基本庫存控制系統,需要計算一些數字以從供應商那裏訂購。重複使用SQL查詢或視圖中的計算列
我希望做的是這樣的查詢:
SELECT [Articles].[ArticleId]
,(SELECT COALESCE(SUM([Quantity]),0) FROM [dbo].[InventoryTable] WHERE [InventoryTable].ArticleId = [Articles].[ArticleId]) AS 'QuantityInStorage'
,(SELECT COALESCE(SUM([Quantity]),0) FROM [dbo].[CustomerOrdersTable] WHERE [CustomerOrdersTable].ArticleId = [Articles].[ArticleId]) AS 'QuantityDeliverToCustomers'
,(SELECT COALESCE(SUM([Quantity]),0) FROM [dbo].[SupplierOrdersTable] WHERE [SupplierOrdersTable].ArticleId = [Articles].[ArticleId]) AS 'QuantityOrderedFromSupplier'
,[Reorderlevel]
,[RefillQuantityToLevel]
,CASE
WHEN [Reorderlevel] <> 0 THEN ([QuantityInStorage]+[QuantityOrderedFromSupplier]-[QuantityDeliverToCustomers])*100/[Reorderlevel] -- compute how important it is to restock on this item
WHEN ([QuantityInStorage]+[QuantityOrderedFromSupplier]-[QuantityDeliverToCustomers]) < 0 THEN -1 -- we don't want the article in storage but need to order it to send it to customers
ELSE 999 -- unimportant, don't order this stuff
END AS 'Importance' -- below zero is very important (need article to send to customer), below 100 is some kind important (refill storage), above 100 is not important
FROM [Articles]
WHERE [QuantityInStorage]-[QuantityDeliverToCustomers]+[QuantityOrderedFromSupplier]<[RefillQuantityToLevel]
ORDER BY [Importance]
我的問題是:我怎樣才能重新使用計算列像我嘗試在我的例子嗎?如果我嘗試這樣,SQL Server總是顯示一個錯誤。
蕩。我搜索了兩個小時而沒有發現 - 謝謝! – Sam 2015-02-09 11:51:10