有人可以告诉我为什么抱怨这个? 我正在使用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'.
为什么要抱怨我的别名?
答案 0 :(得分: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
答案 1 :(得分:0)
您不能在GROUP BY子句中使用别名。 这是由于SQL处理顺序,GROUP BY在SELECT之前处理。 尝试更换:
GROUP BY letters
与
GROUP BY (LEN(word) - LEN(REPLACE(word,'A','')))
答案 2 :(得分: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
希望有所帮助
答案 3 :(得分: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