我认为这COMPUTE
可以应用于SELECT
子句中的列,因此您必须定义别名并使用它们:
Select
col1, sum(col2) AS sum_col2 --- alias
...
Compute
Sum(sum_col2), avg(sum_col2) by col1 ; --- using the alias
而且我不确定您是否想要,by col1
因为您已经按该列分组。如果您想要 的总和和平均值,请从 中sum_col2
删除。by col1
COMPUTE
另一个(与您的问题无关)问题是where year(t1.coldate) = 2012
条件 which is not sargable。我会使用它where coldate >= '20120101' and coldate < '20130101'
,以便使用索引coldate
。所有更改后的查询
...并且在您的评论和一些实验之后(这使得认为与 结合并非易事GROUP BY
)COMPUTE
,也许您应该删除GROUP BY
:
Select
t1.col1, col2
from
table1 t1
join
table2 t2 on t1.col1 = t2.col1
where
coldate >= '20120101' and coldate < '20130101'
order by
col1
Compute
Sum(col2), Avg(col2) by col1 -- for every col1
Compute
Sum(col2), Avg(col2) -- and overall
;
正如@Bogdan Shalean 正确评论的那样,COMPUTE
正在弃用,您应该使用GROUP BY GROUPING SETS
:
Select
t1.col1,
SUM(col2) AS TotalMedicine,
AVG(col2) AS AverageMedicine
from
table1 t1
join
table2 t2 on t1.col1 = t2.col1
where
coldate >= '20120101' and coldate < '20130101'
Group By Grouping Sets
( (col1),
()
)
;
请参阅SQL-Fiddle测试。