SQL将公式应用于AVERAGE值

时间:2013-10-22 16:44:17

标签: sql-server-2008

给出伪表:

+-----+---------------------+------+
| 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)

按日期分组?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以分别为每个标签选择一个总和或平均值,然后在每个单独的查询中选择您想要的操作

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