2017-05-08 45 views
-2

我有一個表campaign如何從表中選擇記錄,其中列的總和等於某個值?

capaign_id | offers_count 
------------------------- 
1   |  1 
2   |  1 
3   |  4 
4   |  3 

我想選擇運動offers_count的,二者之和等於7,也就是運動3和4

+0

您是否想要查找兩個廣告系列的所有組合,其中的offer_count總數是7? – GurV

+0

或者您想查找其所有offers_count總數爲7的所有廣告系列的所有組合? –

+0

不,我想要選擇合計的offer_count總數爲7的廣告系列。@GurwinderSingh – miche

回答

0

一個可能的解決方案可能是

1 )摘下campaign_idoffers_count

YourModel.pluck(:offers_count) 
#=> [[1,1], [2,1], [3,4], [4,3]] 

2)然後解決子集和對第二個問題的元素[第一保持/零參考]

https://stackoverflow.com/a/19488950/4481312

下面的代碼也由SO職位,但我沒能找到線索,現在。

def subset_sum(array, tot) 
    (1..array.size).each_with_object([]) do |n,arr| 
    array.combination(n).each { |a| arr << a if a[0][0].reduce(:+) == tot } 
    end 
end 
+0

謝謝@marmeladze。 – miche

相關問題