0

I have a similar table to this in SQL:

id |tag | entryID
---+----+--------
1  |foo | 0
2  |foo | 0
3  |bar | 3
5  |bar | 3
6  |foo | 3
7  |foo | 3

I want to run a query to count distinct rows in the table (with the id column dropped). The result should look like this (or a transpose of this table):

(tag=foo, entryID=0) | (tag=foo, entryID=3) | (tag=bar, entryID=3)
---------------------+----------------------+---------------------
2                    | 2                    | 2

What should this query look like?

Note: The values in each of the columns are not known beforehand.

3
  • Have you tried anything at all that you can show us to get us started, or are you asking for a quotation for the work Commented Aug 10, 2016 at 0:45
  • Dou know the values for tag and entry beforehand? If so, you can use conditional aggregation. If not, you'll need to combine that approach with dynamic sql. Commented Aug 10, 2016 at 0:46
  • Similar to: stackoverflow.com/questions/5737628/mysql-count-distinct Commented Aug 10, 2016 at 1:34

1 Answer 1

2

You can do this using conditional aggregation:

select sum(tag = 'foo' and entryId = 0) as "tag=foo, entryID=0",
       sum(tag = 'foo' and entryId = 3) as "tag=foo, entryID=3",
       sum(tag = 'bar' and entryId = 3) as "tag=bar, entryID=0"
from t;

However, the normal method is to put the counts in rows, not columns:

select tag, entryId, count(*)
from t
group by tag, entryId;

The rows are much more versatile, because you don't have to list out every combination you might want to match.

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

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.