2016-05-29 37 views
-1

我已经给出了多次,但似乎没有工作。这可能吗?以下是我目前的尝试:如何在公用表格表达式(CTE)中执行SUM()函数

With PrintsPerDayPerEmp(ID,[Month],[Day],[Year], [Number Of Prints]) 
AS 
(Select ID, 
    datepart(month,Agent_Local_Time) as [Month], 
    datepart(day,Agent_Local_Time) as [Day], 
    datepart(year,Agent_Local_Time) as [Year], 
    count(RowID) as [Number of Prints] 
From Table1 
Where Agent_Local_Time >= (getdate()-90) 
Group by datepart(day,Agent_Local_Time), 
    datepart(month,Agent_Local_Time), 
    datepart(year,Agent_Local_Time), 
    ID 
) 
select * 
from PrintsPerDayPerEmp 
where [Number Of Prints] > (sum([Number Of Prints])/90)*3 
order by ID desc 
+0

所以我们展示你的'goes',你到底希望我们做什么? – sagi

+0

对不起:)添加了它。 – RoflWaffle17

+0

我想这里的逻辑显然会给我整列的总和作为一个数字,但我希望它显示发现每个ID的总和....如果这是有道理的。 – RoflWaffle17

回答

0

我假设您正在使用SQL Server,因为getdate()函数。

我不确定你为什么要使用CTE。这似乎完全没有必要。

我的猜测是,你期望sum(count(RowID))是总的总数,但这不是聚合函数的工作方式。 GROUP BY子句会影响所有聚合函数。

我的猜测是,这是你想要的。它使用OVER()子句来控制聚集,并得到一个整体总:

Select Id, 
    datepart(month,Agent_Local_Time) as 'Month', 
    datepart(day,Agent_Local_Time) as 'Day', 
    datepart(year,Agent_Local_Time) as 'Year', 
    count(RowID) as 'Number Of Prints', 
    count(RowID) over() as 'Print Sum' 
From Table1 
Where Agent_Local_Time >= (getdate()-90) 
Group by datepart(day,Agent_Local_Time), 
    datepart(month,Agent_Local_Time), 
    datepart(year,Agent_Local_Time), 
    Id 
Order by Id desc 

或者这样:

Select Id, 
    datepart(month,Agent_Local_Time) as 'Month', 
    datepart(day,Agent_Local_Time) as 'Day', 
    datepart(year,Agent_Local_Time) as 'Year', 
    count(RowID) as 'Number Of Prints', 
    count(RowID) over (partition by Id) as 'Print Sum' 
From Table1 
Where Agent_Local_Time >= (getdate()-90) 
Group by datepart(day,Agent_Local_Time), 
    datepart(month,Agent_Local_Time), 
    datepart(year,Agent_Local_Time), 
    Id 
Order by Id desc 

但是,如果没有一些数据和预期的结果就很难讲。

+0

感谢大家试图帮助 - 这是一个周末假期很长,所以我一直无法对此作出反应/处理。但基本上,我试图找到的结果如下: 1.返回每日ID和每日打印计数,其每日打印计数大于过去90天的ID打印平均值的3倍。 现在,我的查询返回每个ID,每月/每天/每年,以及在过去90天内找到的每个ID的打印计数...问题是我似乎无法获得90天平均值查看是否对于给定的一天,他们的打印计数是平均值的3倍。 这是否更有意义? – RoflWaffle17

0

首先,不要对列别名使用单引号。只对字符串和日期常量使用单引号。在SQL Server中,正确的转义字符是双引号或方括号。

二,group by都是错的。

我认为这基本上是你想要的查询,假设id是雇员ID:

With PrintsPerDayPerEmp([Id],[Month],[Day],[Year], [Number Of Prints], [Print Sum]) 
AS (
     Select Id, datepart(month, Agent_Local_Time) as [Month], 
      datepart(day, Agent_Local_Time) as [Day], 
      datepart(year, Agent_Local_Time) as [Year], 
      count(RowID) as [Number of time per Day], 
      sum(count(RowID)) over() as [Print Sum] 
     From Table1 
     Where Agent_Local_Time >= (getdate() - 90) 
     Group by datepart(day, Agent_Local_Time), 
       datepart(month, Agent_Local_Time), 
       datepart(year, Agent_Local_Time), 
       Id 
    ) 
select * 
from PrintsPerDayPerEmp 
order by Id desc; 
+0

我最新的尝试已被编辑到原始代码发布。 – RoflWaffle17

+0

@ RoflWaffle17。 。 。您已更改查询的逻辑。你不能在'where'子句中使用聚合函数。删除“where”并回答问题。如果您有其他需求,请提出另一个问题。 –

相关问题