在T-SQL中计算DISTINCT值

时间:2017-11-16 00:40:53

标签: sql-server-2008 tsql

我正在尝试计算视图中不同电子邮件地址的数量,但我无法弄清楚语法......这就是我所拥有的:

BEGIN
  SELECT COUNT(*) AS UserCount FROM (
    SELECT DISTINCT EmailAddress 
    FROM viewCohortsAuthorizedByContractor
    WHERE (ListAccess = 1) AND (ContractorId = @id)
  )
END

内部选择工作正常,但如果我尝试添加COUNT,我会收到以下错误:消息156,级别15,状态1,过程rptContractorUsersWithListUserCount,第23行[批处理开始行15] 关键字' END'附近的语法不正确。

我确定这是一个简单的解决方案,我无法弄明白......

2 个答案:

答案 0 :(得分:2)

您不需要子查询。试试这个:

SELECT count(DISTINCT EmailAddress) as UserCount
FROM viewCohortsAuthorizedByContractor
WHERE (ListAccess = 1) AND (ContractorId = @id)

答案 1 :(得分:0)

BEGIN
  SELECT COUNT(*) AS UserCount FROM (
    SELECT DISTINCT EmailAddress 
    FROM viewCohortsAuthorizedByContractor
    WHERE (ListAccess = 1) AND (ContractorId = @id)
  )A   -----give a name for result set
END