2016-06-09 57 views
0
Select AdClick.AdMonth AS DATE, 
(SELECT SUM(AdBudget) FROM AdBudget GROUP BY AdMonth)/
(SELECT SUM(AdClicks) FROM AdClick, AdReport 
WHERE AdReport.AdSourceID != 4 
AND AdReport.AdSourceID = AdClick.AdSourceID 
GROUP BY AdMonth) AS CPC 
FROM AdClick, AdBudget, AdReport 
WHERE AdClick.AdYear = '2016' 
GROUP BY AdClick.AdMonth 

分爲多個值SUM(AdBudget)SUM(AdClicks)具有附着在一個表中分開數月AdMonth值,但我需要劃分具有相同的月份值總和。分組不起作用,因爲我無法將子查詢中的多個值除以具有多個值的另一個子查詢,因此有沒有辦法將AdMonth 1的總和除以AdMonth 1和2的總和2 ...?SQL - 由多個值

僅供參考:我正在使用代碼來創建ColdFusion圖表,但這些查詢在ColdFusion文檔中調用,因此與圖表配合使用的ColdFusion解決方案並未脫離表格。

回答

1

應該是這樣的。內部將月份和源ID連接在一起,並按月份分組:

SELECT AdClick.AdMonth AS `DATE` 
     , SUM(AdBudget.AdBudget) 
     , SUM(AdClick.AdClicks) 
     , SUM(AdBudget.AdBudget)/SUM(AdClick.AdClicks) 
FROM AdClick 
      INNER JOIN AdBudget ON AdClick.AdMonth = AdBudget.AdMonth 
      INNER JOIN AdReport ON AdReport.AdSourceID = AdClick.AdSourceID 
WHERE AdClick.AdYear = '2016' 
AND  AdReport.AdSourceID != 4 
GROUP BY AdClick.AdMonth 
+0

我需要劃分具有相同AdMonth的總和,可以將其添加到代碼中嗎? –

+0

我已更新答案.. – scaisEdge

+0

謝謝!我用cfloops算出了我的問題,但是謝謝你的答案。 –