2013-10-31 21 views
0

的子集:SQL查詢來發現對於這個表給定表

http://www.w3schools.com/sql/trysql.asp?filename=trysql_func_sum

我怎麼會產生OrderIds的列表,其中數量的總和至多爲90。如何表達SQL一樣嗎?對於相同的查詢可以有多個答案。你將如何生成它們?在某種程度上,這對我來說也是揹包問題,但我不知道如何在SQL中表達同樣的問題。

你可能需要在網頁中

+0

你應該從鏈接的問題添加數據。然後鏈接斷開,這個問題對於未來的訪問者是沒有用的。 –

+1

我不認爲只用SQL就可以生成* all *可能的解決方案。 – user2864740

+0

我已更新該問題。 – Rahul

回答

0

您可以用遞歸CTE這樣做是Postgres的執行查詢

SELECT * FROM OrderDetails; 

,但是這將是大量低效:

With Recursive search_orders(maxid, quantity, used) AS (
    Select 
     od.OrderDetailsID, 
     od.quantity, 
     array[od.OrderDetailsID] 
    from 
     OrderDetails od 
    Where 
     quantity < 90 
    Union All 
    Select 
     od.OrderDetailsID, 
     sod.quantity + od.quantity, 
     used || od.OrderDetailsID 
    From 
     OrderDetails od, 
     search_orders sod 
    Where 
     od.OrderDetailsID > sod.maxid and 
     od.quantity < 90 - sod.quantity 
) 
Select 
    used, 
    quantity 
From 
    search_orders sod 
Where 
    not exists (
     select 'x' 
    from 
     OrderDetails od 
    Where 
     Not od.OrderDetailsID = Any(used) and 
     od.quantity < 90 - sod.quantity 
    )  

如果你想要所有的組合,無論你是否可以添加另一個項目而不需要o版本的數量限制,您可以刪除最後一個where子句

Example SQL Fiddle

0
SELECT OrderID, SUM(Quantity) AS TotalItemsOrdered 
FROM OrderDetails 
GROUP BY OrderID 
HAVING SUM(Quantity)<= 90 
+0

看來OP想要一個OrderIds列表,其中數量總和最多爲90。基於問題中的揹包*參考確實需要一個訂單ID列表。奇怪的請求 –

+1

查詢將返回每個orderid whos數量<= 90。我需要一個orderid列表,其中該列表中的數量總和小於等於90. – Rahul

+0

這不是上述查詢的作用嗎?以上查詢顯示總數量小於90的151個訂單ID。 – Linger