2017-08-30 112 views
1

我想選擇一列值乘以另一列SQL SERVER - 乘另一列

select 
    sum(CS.revenue * count(C.subid)) as [total_revenue] 
from campaigns_history CH 
LEFT OUTER JOIN campaign_sends CS ON CS.campaign_historyID = CH.id 
LEFT OUTER JOIN c C ON C.subid = cast(CS.id as nchar(255)) 
WHERE CH.id=19 

的計數總和的數列值的SELECT SUM我得到這個錯誤:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

我該怎麼做?

感謝和快樂的編程! :)

+1

基本上你得到這樣做的原因是因爲你試圖通過一個非集合因爲行的量是不一樣的,SQL-SRV不喜歡這個乘以一個aggergate(COUNT) 。我會用下面的解決方案(通過Eli),因爲這是最佳實踐 –

+0

謝謝@MikeMirabelli – Eli

+0

@MikeMirabelli,@Eli--請檢查我自己的答案,我在解釋問題時沒有讓自己清楚。 'sum(ca)* count(af)'不同於'sum(ca * count(af))' - 第一個是將總和'ca'乘以'af'的次數,第二個是「ca」值的​​總和乘以「af」的數量......這有意義嗎?對不起我生鏽的英語。 –

回答

1

您需要的SUMCOUNT分開 - 這樣:

select 
    SUM(CS.revenue) * COUNT(C.subid) AS [total_revenue] 
FROM campaigns_history CH 
LEFT OUTER JOIN campaign_sends CS ON CS.campaign_historyID = CH.id 
LEFT OUTER JOIN c C ON C.subid = CAST(CS.id as NCHAR(255)) 
WHERE CH.id=19 
0

你的標題已經給你一個答案:)計算總和和計數相乘。

SELECT Sum(CS.revenue) * Count(C.subid) as [total_revenue] 
FROM campaigns_history CH 
    LEFT OUTER JOIN campaign_sends CS ON CS.campaign_historyID = CH.id 
    LEFT OUTER JOIN c C ON C.subid = cast(CS.id as nchar(255)) 
WHERE CH.id = 19 
0

試試這個:

select 
    sum(
     CS.revenue * 
     (select 
      count(c.subid) 
     from c 
     where c.subid = cast(CS.id as nchar(255)) 
     ) as [total_revenue] 
from campaigns_history CH 
LEFT OUTER JOIN campaign_sends CS ON CS.campaign_historyID = CH.id 
WHERE CH.id=19 
0

對不起球員,你的答案didint適合我的需要。
它主要是我的錯,因爲我沒有讓自己清楚......

我真正需要的是CS.revenue值乘以的C.subid計數的總和..這是否有道理?對不起我生鏽的英語。

爲了讓詞首先乘以CS.revenueC.subid的總數,然後才能得出結果。

我想出了一個查詢來返回我期望的結果。

SELECT 
sum(css.total_revenue) 
from (SELECT top 1 * from campaign_sends) as CS 
INNER JOIN (
    select 
    CS.revenue * count(C.subid) as [total_revenue] 
    from campaigns_history CH 
    LEFT OUTER JOIN campaign_sends CS ON CS.campaign_historyID = CH.id 
    LEFT OUTER JOIN c C ON C.subid = cast(CS.id as nchar(255)) 
    WHERE 
    CH.id=19 
    GROUp BY CS.revenue 
) as css ON css.total_revenue is not null