1

I am trying to count the number of distinct email addresses in a view, but I can't figure out the syntax... Here's what I have:

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

The inner select works fine, but if I try adding the COUNT, I get the following error: Msg 156, Level 15, State 1, Procedure rptContractorUsersWithListUserCount, Line 23 [Batch Start Line 15] Incorrect syntax near the keyword 'END'.

I'm sure there's a simple solution, I just can't figure it out...

4
  • 1
    You forgot to specify an alias for your subquery - SELECT COUNT(*) AS UserCount FROM (...) as Q. The keyword AS isn't necessary - SELECT COUNT(*) AS UserCount FROM (...) Q. In your case SQLServer think that END is your alias. Early SteveB showed is more rightly query for your case. Commented Nov 16, 2017 at 4:49
  • Knew it was something simple. Just didn't think of an alias given that there weren't any clauses at the end (Where, Order By). Commented Nov 16, 2017 at 15:18
  • The syntax of TSQL requires that you specify an alias for a subquery in any case. Commented Nov 16, 2017 at 15:38
  • I said about subqueries which are located in the FROM-block. Commented Nov 16, 2017 at 15:44

2 Answers 2

3

You don't need the subquery. Try this:

SELECT count(DISTINCT EmailAddress) as UserCount
FROM viewCohortsAuthorizedByContractor
WHERE (ListAccess = 1) AND (ContractorId = @id)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.