2013-10-22 75 views
0

給出的僞表:SQL應用公式AVG值

+-----+---------------------+------+ 
| tag | data    | read | 
+-----+---------------------+------+ 
| A | 2013-10-10 15:00:00 | 1345 | 
+-----+---------------------+------+ 
| A | 2013-10-10 15:15:00 | 3454 | 
+-----+---------------------+------+ 
| A | 2013-10-10 15:30:00 | 2345 | 
+-----+---------------------+------+ 
| A | 2013-10-10 15:45:00 | 1132 | 
+-----+---------------------+------+ 
| B | 2013-10-10 15:00:00 | 6234 | 
+-----+---------------------+------+ 
| B | 2013-10-10 15:15:00 | 5432 | 
+-----+---------------------+------+ 
| B | 2013-10-10 15:30:00 | 4563 | 
+-----+---------------------+------+ 
| B | 2013-10-10 15:45:00 | 5432 | 
+-----+---------------------+------+ 

是否有可能只適用於使用SQL下面的公式?

實施例:

result=AVG(A)-(AVG(B)+AVG(C)) 

result=AVG(A)+AVG(B) 

由日期分組?

回答

1

應該計算結果

這裏有SqlFiddle演示。

select (AVG(case when tag = 'A' then read end) + AVG(case when tag = 'B' then read end)) 'result', data 
from TBL 
group by data 
+0

它工作正常的操作選擇。但必須刪除「其他0」,因爲它會影響平均計算,所以'... AVG(CASE當標籤='A'然後讀完)...' –

+0

你是對的。我糾正了它。 – sqlint

0

您可以單獨選擇每個標籤的總和或平均,然後用你想在其中的每臺個人查詢

select (select SUM([read]) from table where tag = 'A') + 
    (select SUM([read]) from table where tag = 'B')