按案例陈述的结果分组

时间:2013-08-02 15:08:38

标签: sql-server sql-server-2005 group-by case aggregate

我正在尝试使用聚合函数和case语句在我的select和group中使用case语句在SQL Server 2005中工作,但我似乎错过了一些东西。

declare @td int
set @td = 20130731

select 
    count(*) as total,
    case
       when dateadd(s, cdm.[StartTime], '19700101') >= '2013-07-31 00:00:00.000' and dateadd(s, cdm.[StartTime], '19700101') < '2013-07-31 01:00:00.000' 
        then '0-1'
    end as timestripe
FROM 
    [EXTERNAL_CDR].[dbo].[CDRMAIN] as cdm
WHERE 
    cdm.LocalDay = @td
    AND cdm.targetnum IN ('500','600')
GROUP BY
    timestripe

count(*)部分有点弱,我知道但问题出在group by语句中。当我运行此查询时,出现以下错误:

  

Msg 207,Level 16,State 1,Line 15
  列名称'timestripe'无效。

似乎case语句是错误的根本原因,但我不必编写子查询或加入只是为了让它工作。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

对于此查询,logical Processing Order of the SELECT statement为:

  • FROM,
  • WHERE
  • GROUP BY和
  • 选择

由于SELECT位于GROUP BY之后,SELECT子句中定义的所有别名(包括timestripe)都无法在上一步(GROUP BY)中使用。

一种解决方案可能是:

SELECT x.timestripe, COUNT(*) AS Cnt
FROM (
select 
    case
       when dateadd(s, cdm.[StartTime], '19700101') >= '2013-07-31 00:00:00.000' and dateadd(s, cdm.[StartTime], '19700101') < '2013-07-31 01:00:00.000' 
        then '0-1'
    end as timestripe
FROM 
    [EXTERNAL_CDR].[dbo].[CDRMAIN] as cdm
WHERE 
    cdm.LocalDay = @td
    AND cdm.targetnum IN ('500','600')
) x
GROUP BY x.timestripe

答案 1 :(得分:0)

您无法在GROUP BY中引用别名,因此只需将整个case语句放入其中即可。保留“as timestripe”部分。

declare @td int
set @td = 20130731

select 
    count(*) as total,
    case
       when dateadd(s, cdm.[StartTime], '19700101') >= '2013-07-31 00:00:00.000' and dateadd(s, cdm.[StartTime], '19700101') < '2013-07-31 01:00:00.000' 
        then '0-1'
    end as timestripe
FROM 
    [EXTERNAL_CDR].[dbo].[CDRMAIN] as cdm
WHERE 
    cdm.LocalDay = @td
    AND cdm.targetnum IN ('500','600')
GROUP BY
    case
       when dateadd(s, cdm.[StartTime], '19700101') >= '2013-07-31 00:00:00.000' and dateadd(s, cdm.[StartTime], '19700101') < '2013-07-31 01:00:00.000' 
        then '0-1'
    end