0

所以我有一堆数据,我已经将它按列名和月份分组。这是我到目前为止的 SQL 查询

TestName 是列名,POE 业务规则/提交每列出现多次 VExecutionGlobalHistory 是表的名称,我使用 Microsoft SQL Server Management Studio 2010

    select  
   year(dateadd(mm,datediff(mm,0,StartTime),0)),
    datename(month,dateadd(mm,datediff(mm,0,StartTime),0)),TestName,

    Case WHEN Testname = 'POE Business Rules' THEN (count(TestName)*36) WHEN TestName =         'Submit' THEN (count(TestName)*6) ELSE 0 END

    From VExecutionGlobalHistory

    group by
    year(dateadd(mm,datediff(mm,0,StartTime),0)),
    datename(month,dateadd(mm,datediff(mm,0,StartTime),0)),TestName

这个查询给了我这种格式

  2013 |APRIL| POE Business Rules| 1044
  2013 |APRIL| SUBMIT            | 96
  2013 |JULY | POE Business Rules| 216
  2013 |JULY | SUBMIT            | 102

我想要一个最终格式,它只有每个月的计数总和

   2013|APRIL|SUM of the counts or (1044 + 96)
   2013|JULY |SUM of the counts or (216 + 102)

我不需要 testname 只是每月计数的总和

我曾尝试在案例之前添加 SUM,但出现 "Cannot perform an aggregate function on an expression containing an aggregate or a subquery."错误。

关于另一种方法的任何建议?

4

3 回答 3

3

你可以只使用一个子查询:

SELECT Year_, Month_, SUM(Counts)
FROM (
        SELECT YEAR(DATEADD(MM,DATEDIFF(MM,0,StartTime),0))'Year_'
              ,DATENAME(MONTH,DATEADD(MM,DATEDIFF(MM,0,StartTime),0))'Month_'
              ,TestName
              ,CASE WHEN Testname = 'POE Business Rules' THEN (count(TestName)*36) 
                    WHEN TestName = 'Submit' THEN (COUNT(TestName)*6) 
                    ELSE 0 
               END 'Counts'
        FROM VExecutionGlobalHistory
        GROUP BY YEAR(DATEADD(MM,DATEDIFF(MM,0,StartTime),0))
                ,DATENAME(MONTH,DATEADD(MM,DATEDIFF(MM,0,StartTime),0))
                ,TestName
        )sub
GROUP BY Year_, Month_
ORDER BY CAST(CAST(Year_ AS CHAR(4)) + Month_ + '01' AS DATETIME) 

更新:添加 ORDER BY 以首先按 YEAR/MONTH 排序。

于 2013-07-16T16:29:59.377 回答
0

就像是

Select SumYear,SomeMonth,Sum(SumCounts) From
(
select  
   year(dateadd(mm,datediff(mm,0,StartTime),0)) as SumYear,
    datename(month,dateadd(mm,datediff(mm,0,StartTime),0)) as SumMonth,TestName,

    Case WHEN Testname = 'POE Business Rules' THEN (count(TestName)*36) WHEN TestName =         'Submit' THEN (count(TestName)*6) ELSE 0 END as sumCounts

    From VExecutionGlobalHistory

    group by
    year(dateadd(mm,datediff(mm,0,StartTime),0)),
    datename(month,dateadd(mm,datediff(mm,0,StartTime),0)),TestName ) sums
Group by SumYear,SumMonth

应该这样做

于 2013-07-16T16:29:38.320 回答
0

您的逻辑可能过于复杂。听起来您只需要按(年,月)分组的加权总和。带有“POE 业务规则”的行价值 36,带有“提交”的行价值 6,其他所有的价值 0。

SELECT
  YEAR(StartTime),
  DATENAME(month,DATEADD(month,MONTH(StartTime)-1,0)),
  SUM(
    CASE Testname
      WHEN 'POE Business Rules' THEN 36
      WHEN 'Submit'             THEN 6
      ELSE 0
    END
  )
FROM VExecutionGlobalHistory
GROUP BY YEAR(StartTime),MONTH(StartTime)
ORDER BY YEAR(StartTime),MONTH(StartTime)
于 2013-07-16T19:24:52.587 回答