声明变量

时间:2016-04-19 19:24:38

标签: sql sql-server tsql

我收到错误消息:

  

Msg 164,Level 15,State 1,Line 18
  每个GROUP BY表达式必须包含至少一个不是外部引用的列

来自这个T-SQL代码:

DECLARE @CLIENT_COUNT INT

SELECT @CLIENT_COUNT = COUNT(CLT_NBR) FROM CLIENT

SELECT 
    CASE 
       WHEN STATUS = 3 
          THEN 'CATEGORY1' 
          ELSE 'CATEGORY2' 
    END AS Category,
    COUNT(*) AS COUNT,
    @CLIENT_COUNT as [Total CLIENT],
    COUNT(*) / @CLIENT_COUNT as PERCENTAGE
FROM 
    CLIENT_STATUS
WHERE 
    STATUS IN (3, 8)
GROUP BY 
    STATUS, @CLIENT_COUNT 

你能帮我解决一下吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

你的语法错了。您需要在FROM之前放置所有需要返回的值。

DECLARE @CLIENT_COUNT INT

SELECT @CLIENT_COUNT = COUNT(CLT_NBR)
FROM CLIENT

SELECT CASE 
    WHEN STATUS = 3
        THEN 'CATEGORY1'
    ELSE 'CATEGORY2'
    END AS Category
     , COUNT(STATUS) AS StatusCount
     , @CLIENT_COUNT AS [Total CLIENT]
     , COUNT(STATUS) / @CLIENT_COUNT AS PERCENTAGE
FROM CLIENT_STATUS
WHERE STATUS IN (
       3
      ,8
    )
GROUP BY STATUS