2011-02-10 68 views
1

如果不能在我的MS SQL存儲過程中使用數組,我無法計算出計算公式的有效方法。使用不同數量的輸入在MS SQL Server中進行高效計算

背景....

select child_id, sum(quantity) as quantity 
    from table 
    where parent_id = @parent_id 

回報是這樣的....

child_id  quantity 
100   50000 
200   60000 
300   45000 
400   30000 
500   15000 

這是一個簡單的SQL公式來說明什麼,我需要幫助。數學並不重要(好吧,如果它沒有任何意義 - 它簡化,以表明我需要如何使用從上面的總結量)...

set @result = (2 * LOG(50000)) + LOG(60000) + LOG(45000) + LOG(30000) + LOG(15000) 

對於上述每個child_id的,我想要執行一個(select child_id,@result)。請注意,「活動」child_id的總計數量與其他child_ids(2 * LOG())的總和數量不同。此外,child_id的計數在2到20之間變化。如果只有2個child_ids,則@result將爲=(2 * LOG(50000)+ LOG(60000)。對於你可以提供的任何建議很多

+0

在上面的例子中,child_id 200的結果是什麼? – 2011-02-10 16:47:29

+0

Matt,Joe,Martin - 謝謝。我必須再考慮一下,以確定CTE方法是否能用我的非簡化算法工作(或如何工作)。 Matt,回答你的問題 - child_id 200的結果是=(2 * LOG(60000))+ LOG(50000)+ LOG(45000)+ LOG(30000)+ LOG(15000)。再次感謝你們。 – karman 2011-02-10 19:23:49

回答

1

假設至少SQL 2005爲CTEs。我瘋狂的方法是,我會得到所有日誌值的單一總和,然後爲每個孩子添加日誌值實現總和的2 *(這個孩子的值)部分。

;with cteQuantity as (
    select child_id, sum(quantity) as quantity 
     from table 
     where parent_id = @parent_id 
     group by child_id 
), 
cteAllLogs as (
    select sum(log(quantity)) as log_sum 
     from cteQuantity 
) 
select q.child_id, log(q.quantity) + l.log_sum as result 
    from cteQuantity q 
     cross join cteAllLogs l 
+0

是的,我們正在思考。令人放心的是我們正在提供相同的答案:) @karman,Joe的CTE可能是更乾淨的方式,假設你沒有與SQL Server 2000一起苦苦掙扎。 – 2011-02-10 17:03:15

1

嗯,這可能前往你在正確的方向,但我們可能需要更多一點的細節計算:

DROP TABLE #results 
CREATE TABLE #results (parent_id INTEGER, child_id INTEGER, quantity FLOAT) 
INSERT INTO #results VALUES (10, 100, 50000) 
INSERT INTO #results VALUES (10, 200, 60000) 
INSERT INTO #results VALUES (10, 300, 45000) 
INSERT INTO #results VALUES (10, 400, 30000) 
INSERT INTO #results VALUES (10, 500, 15000) 

SELECT 
    child_id, quantity, LOG(quantity) + (SELECT SUM(LOG(quantity)) FROM #results subquery WHERE #results.parent_id = subquery.parent_id) 
FROM 
    #results