10

我有以下 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

我收到以下错误:

消息 207,级别 16,状态 1,第 15 行
无效的列名称“DiffDate”。

这个查询背后的想法是我想在多少天内得到解决(关闭)的案例数量。

例子:

1 = 3 例

2 = 50 例

3 = 20 例

我怎样才能做到这一点?

4

5 回答 5

21

您需要在子句中使用整个表达式,GROUP BY或者只需将整个语句包装在子查询中,然后对外部语句进行分组。

不能在语句的同一级别上创建ALIAS的子句上使用的原因是,在创建的子句之前执行。GROUP BYSELECTGROUP BYSELECTALIAS

这是 SQL 操作顺序:

  • FROM 子句
  • WHERE 子句
  • GROUP BY 子句
  • HAVING 子句
  • 选择子句
  • ORDER BY 子句

试试这个查询,

SELECT  COUNT(CaseId),
        DiffDate
FROM
        (
            select  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'
        ) sub
Group By DiffDate
于 2013-05-05T07:03:58.030 回答
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)
于 2013-05-05T07:43:51.337 回答
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 的新手,所以也许我没有正确掌握它。我看到上面的评论有确切的语法,但我不知道它是否正确......

于 2015-03-23T21:04:49.007 回答
0

这是实施讨论的一个简单示例

select selectResualt.num ,count(selectResualt.num) as count  
from (select src_num As num from mytable  UNION ALL select dis_num As num from mytable) as selectResualt
group by selectResualt.num
order by count(selectResualt.num) DESC;>
于 2015-04-29T21:40:23.143 回答
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
于 2016-12-13T18:55:19.433 回答