子选择失败,但视图有效

时间:2011-05-10 14:44:25

标签: sql sql-server sql-server-2005 tsql

我希望运行一个查询并从中获得结果。但是,MSSQL抱怨GROUP关键字附近出现语法错误。 我希望能做到以下几点。

  SELECT COUNT(*) AS cnt,Field_2
    FROM (SELECT DISTINCT Field_1, Field_2 
            FROM Table_1)
GROUP BY Field_2 
  HAVING COUNT(*) > 1

相反,我必须使用查询

创建一个View_1视图
SELECT DISTINCT Field_1, Field_2 
  FROM Table_1

然后做一个

  SELECT COUNT(*) AS cnt, Field_2
    FROM View_1
GROUP BY Field_2 
  HAVING COUNT(*) > 1

问题是为什么,在我看来它基本上是相同的SQL。

注意:已更改字段,表格和视图名称以保护无辜者。 ; - )

2 个答案:

答案 0 :(得分:13)

SQL Server要求您为派生表/内联视图指定表别名:

  SELECT COUNT(*) AS cnt, 
         x.Field_2
    FROM (SELECT DISTINCT Field_1, Field_2 
            FROM Table_1) AS x
GROUP BY x.Field_2 
  HAVING COUNT(*) > 1

答案 1 :(得分:0)

OMG小马的回答是100%正确的。

我认为这会显示相同的结果,但我现在无法测试:

SELECT COUNT(DISTINCT Field_1) AS cnt
     , Field_2
FROM Table_1
GROUP BY Field_2 
HAVING COUNT(DISTINCT Field_1) > 1