Search code examples
t-sqlcountconditional-statementsdistinct

TSQL Count 'Where' Condition


How do I implement the 'meaning' of the following psuedo-SQL statement:

COUNT(distinct id where attribute1 > 0)

In other words, how do I make conditional, distinct counting statements?

Thanks!


Solution

  • Well, if you can filter the entire query, then LittleBobbyTables already has the answer for you. If not, you can get that column like so:

    count(distinct case when attribute1 > 0 then id end) -- implicit else null