0

有人能告诉我为什么这是抱怨吗?我正在使用 SQL Server,有一个名为 test 的表和一个名为 word 的列

这是我的查询:

SELECT TOP 1
COUNT(*) AS count, 
(LEN(word) - LEN(REPLACE(word,'A',''))) AS letters
FROM dbo.TEST 
WHERE 
word LIKE '******' 
GROUP BY letters 
ORDER BY count DESC

这是结果错误:

Msg 207, Level 16, State 1, Line 7
Invalid column name 'letters'.

为什么抱怨我的别名?

4

4 回答 4

2

您不能在 GROUP BY 中使用别名,请使用相同的计算列:

SELECT TOP 1
COUNT(*) AS count, 
(LEN(word) - LEN(REPLACE(word,'A',''))) AS letters
FROM dbo.TEST 
WHERE 
word LIKE '******' 
GROUP BY (LEN(word) - LEN(REPLACE(word,'A','')))
ORDER BY count DESC
于 2013-07-24T14:36:52.950 回答
0

在查询中更改分组依据

   SELECT TOP 1
            COUNT(*) AS count ,
            ( LEN(word) - LEN(REPLACE(word, 'A', '')) ) AS letters
    FROM    dbo.TEST
    WHERE   word LIKE '******'
    GROUP BY ( LEN(word) - LEN(REPLACE(word, 'A', '')) )
    ORDER BY count DESC
于 2013-07-24T14:40:41.593 回答
0

不能在 GROUP BY 子句中使用别名。这是由于 SQL 处理顺序,GROUP BY 在 SELECT 之前处理。尝试更换:

GROUP BY letters

GROUP BY (LEN(word) - LEN(REPLACE(word,'A','')))
于 2013-07-24T14:38:12.550 回答
0

您不能在查询中使用别名。你需要的是:

SELECT TOP 1
COUNT(*) AS count, 
(LEN(word) - LEN(REPLACE(word,'A',''))) AS letters
FROM dbo.TEST 
WHERE 
word LIKE '******' 
GROUP BY (LEN(word) - LEN(REPLACE(word,'A','')))
ORDER BY count DESC

希望有帮助

于 2013-07-24T14:39:51.630 回答