在SQL Server 2008中通过子句错误计算

时间:2013-05-26 14:59:20

标签: sql database sql-server-2008

我遇到这个计算条款

的问题

该陈述是一个简单的选择

Select 
    col1, sum(col2) 
from 
    table1 t1
join
    table2 t2 on t1.col1=t2.col1
where 
    year(t1.coldate) = 2012
Group by 
    col1
order by 
    col1
Compute 
    Sum(col2), avg(col2) by col1

我不断收到的错误消息是

  

Msg 411,Level 16,State 1,Line 1
  COMPUTE子句#1,聚合表达式#1不在选择列表中..

这是我的完整代码sqlfiddle

我想要的是显示2012年药品销售年份的TransactionID和TotalMedicine(来自销售药品的数量)。还要计算药品的数量和平均销售量。

2 个答案:

答案 0 :(得分:3)

我认为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条件不是 sargable 。我将使用此where coldate >= '20120101' and coldate < '20130101',因此将使用coldate上的索引。所有更改后的查询

...在您的评论和一些实验(认为将GROUP BYCOMPUTE结合起来认为并非易事)之后,您可能应该删除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 测试。

答案 1 :(得分:0)

您需要make your clauses match,所以请尝试:

Select 
    col2, sum(col2)  
from 
    table1 t1 
join 
    table2 t2 on t1.col1 = t2.col1 
where 
    year(t1.coldate) = 2012 
Group by 
    col1 
order by
    col1 
Compute 
    Sum(col2), avg(col2) by col1

或类似的东西,我会给你一个确切的答案,但需要更多细节。