此嵌套查询的结构有什么问题?

时间:2019-03-08 06:54:08

标签: sql sql-server tsql nested

我正在使用SQL Server 2014,并且有以下T-SQL查询:

SELECT 
    COUNT (xx.[Email]), xx.[StayID] 
FROM
    (SELECT 
         COUNT (x.[RepID]),x.[StayID], x.[Email], x.[RepID]
     FROM
         (SELECT 
              *, 
              ([Email] + CONVERT(VARCHAR(10), [Arrival Date], 20)) AS 'RepID' 
          FROM [Table1]
          WHERE [Arrival Date] BETWEEN '2015-07-01' AND '2018-06-30'
            AND [Email] <> '') x
    GROUP BY 
        x.[StayID], x.[Email], x.[RepID]
    HAVING
        COUNT(x.[RepID]) > 1) xx
GROUP BY 
    xx.[StayID], xx.[Email]
HAVING 
    COUNT(xx.[Email]) > 1

我收到以下错误消息:

  

未为“ xx”的第1列指定列名。

我在这里做错了什么?

我还希望将查询更改为CTE。那会是解决方案吗?

3 个答案:

答案 0 :(得分:2)

尝试一下-修改了您的查询,并将名称指定为xx第一列(RepIdCount):

SELECT COUNT (xx.[Email]), xx.[StayID]
FROM (    
  SELECT COUNT (x.[RepID]) as RepIDCount, x.[StayID], x.[Email], x.[RepID]
  FROM (
    SELECT *, ([Email] + CONVERT(varchar(10), [Arrival Date], 20)) as 'RepID' 
    FROM [Table1]
    WHERE [Arrival Date] between '2015-07-01' and '2018-06-30'
    AND [Email] <> ''
  ) x
  GROUP BY x.[StayID], x.[Email], x.[RepID]
  Having Count(x.[RepID]) > 1
) xx
GROUP BY xx.[StayID], xx.[Email]
Having Count(xx.[Email]) >  1

答案 1 :(得分:0)

我会说您以一种更好的方式重写了查询,但是查询中的问题在下一行

SELECT COUNT (x.[RepID]), x.[StayID], x.[Email], x.[RepID]

您可以删除 COUNT个(x。[RepID])语句,因为该语句未在您的父Select语句中使用,或者您给了一个如下所示的别名

SELECT COUNT (x.[RepID]) as RepCount, x.[StayID], x.[Email], x.[RepID]

答案 2 :(得分:0)

如果您运行以下简单查询:

select count(*) from some_table

您会注意到输出中的结果集的列名称为“ No column name”。

SQL Server不会为聚合函数生成默认的列名。 因此,表xx的第一列(也是唯一列),即

COUNT (x.[RepID]),x.[StayID], x.[Email], x.[RepID]

没有名字。您可能没有包含未命名列的子查询。给它起个名字:

 COUNT (x.[RepID]) as cnt ,x.[StayID], x.[Email], x.[RepID])

顺便问一下,为什么要麻烦在COUNT中键入所有列名?

  1. 可以是你