我有以下T-SQL查询:
select
count(CaseId),
(SELECT DATEDIFF(day,CreateDate,LastActivityDate)) AS DiffDate
from
VW_Case_Analysis
where
CaseStatus = 'C'
and LastActivityDate between '2013-4-1 00:00:00.000' and '2013-4-30 23:59:59.000'
Group By
DiffDate
我收到以下错误:
Msg 207,Level 16,State 1,Line 15
列名称“DiffDate”无效。
这个查询背后的想法是我希望在多少天内解决(关闭)案例数量。
示例:
天
1 = 3例
2 = 50例
3 = 20例
我怎样才能做到这一点?
答案 0 :(得分:18)
您需要在GROUP BY
子句中使用整个表达式,或者只是将整个语句包装在子查询中并对外部语句进行分组。
您无法在ALIAS
语句的同一级别创建的GROUP BY
子句上使用SELECT
的原因是因为GROUP BY
之前执行创建SELECT
的{{1}}子句。
这是SQL操作顺序:
尝试此查询,
ALIAS
答案 1 :(得分:3)
您不能在group by子句中使用别名。
使用派生表或在您的情况下简单地删除第二个SELECT。
select
count(CaseId),
DATEDIFF(day,CreateDate,LastActivityDate) AS DiffDate
from
VW_Case_Analysis
where
CaseStatus = 'C'
and LastActivityDate between '2013-4-1 00:00:00.000' and '2013-4-30 23:59:59.000'
Group By
DATEDIFF(day,CreateDate,LastActivityDate)
答案 2 :(得分:0)
这不会给你带来相同的结果吗?
select Count(CaseId),
DATEDIFF(day,CreateDate,LastActivityDate) AS DiffDate
from VW_Case_Analysis
where CaseStatus = 'C' and
LastActivityDate between '2013-4-1 00:00:00.000' and '2013-4-30 23:59:59.000'
GROUP BY DATEDIFF(day,CreateDate,LastActivityDate)
我是SQL的新手,所以也许我没有正确把握它。我看到上面的评论带有确切的语法,但我不知道它是否正确......
答案 3 :(得分:0)
您可以使用CROSS APPLY
创建别名并在GROUP BY
子句中使用它,如下所示:
select
count(CaseId),
DiffDate
from
VW_Case_Analysis
cross apply
(SELECT DATEDIFF(day,CreateDate,LastActivityDate) AS DiffDate) Alias
where
CaseStatus = 'C'
and LastActivityDate between '2013-4-1 00:00:00.000' and '2013-4-30 23:59:59.000'
Group By
DiffDate