1

I have a table like this from which I want to count of recurrences per Username. I would like to count how many distinct Type are there with Amount <> 0 per user:

+----------+-------------+--------+
| Username |    Type     | Amount |
+----------+-------------+--------+
| abc      | New         |      1 |
| abc      | New         |      1 |
| abc      | Old         |      1 |
| def      | New         |      1 |
| def      | Old         |      0 |
| def      | Refurbished |      1 |
| ijk      | New         |      1 |
| ijk      | Old         |      2 |
| ijk      | Refurbished |      3 |
+----------+-------------+--------+

My result should look something like this:

+----------+---------------+
| Username | DistinctCount |
+----------+---------------+
| abc      |             2 |
| def      |             2 |
| ijk      |             3 |
+----------+---------------+

..where [Username] abc has 2 distinct [Type] with [Amount] not equal to 0.

I have tried SELECT DISTINCT Type, Username, SUM(CASE WHEN Amount <> 0 THEN 1 ELSE 0 END) FROM tblBase GROUP BY Type, Username but it's not yielding the desired result.

3 Answers 3

4

Use COUNT DISTINCT with CASE:

SELECT
    Username,
    DistinctCount = COUNT(DISTINCT CASE WHEN Amount <> 0 THEN Type END)
FROM #tbl
GROUP BY Username;

The difference with using WHERE clause is that, this will return rows with 0 DistinctCount, while the WHERE clause will not.

DEMO

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! This is perfect!
It's also the worst solution, isn't it? It's inefficient because you're considering all rows, even when zero. I bet this would run worse in the majority of use cases...
@MattG, maybe. But this is completely different from yours and Backtrack's solution using the WHERE condition. If he intend to exclude 0 rows, then the WHERE clause would be correct and this one's wrong. Otherwise, it's the only correct solution here.
3
 SELECT Username, COUNT(DISTINCT Type) AS DistinctCount
    FROM tblBase  WHERE Amount <> 0 
    GROUP BY Username

I would say, use Amount <> 0 in Where and group by using username. And use distinct to get the count

Comments

3

According to your output, you want one row per username. That means you want to group by username. You want to count the number of distinct types by username, and there's an aggregate function for that. Try this:

SELECT    username, 
          COUNT(DISTINCT Type) as counted 
FROM      tblBase 
WHERE     Amount <> 0 
GROUP BY  username

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.