bt82
bt82

Reputation: 11

SQL Count for Each Repeated Number in Column

I have this

m_id    p_id
112      8
340      8
928     16
190     16
290     16
... etc

How do I get this?

p_id    count(p_id)
8          2
16         3

I'm confused because I also want to make sure that it is counting the p_id while keeping the m_id values distinct.

Help please and thank you :)

Upvotes: 0

Views: 45

Answers (2)

mjavon
mjavon

Reputation: 237

I believe you want something like this:

SELECT p_id, count(distinct m_id) from myTable group by p_id;

That's for if you want to count the number of distinct m_id's that are associated with each p_id, if you only want to count the number of p_id's in the table, drop the distinct keyword.

Upvotes: 1

Fuzzy
Fuzzy

Reputation: 3810

Sample data

  CREATE TABLE #temp
                  (
             m_id INT, p_id INT
                  );

INSERT INTO #temp
VALUES
       (112, 8
       ),
       (340, 8
       ),
       (928, 16
       ),
       (190, 16
       ),
       (290, 16
       );

Query:

SELECT p_id, COUNT(*) [count(p_id)]
FROM #temp
GROUP BY p_id;

Result: enter image description here

Upvotes: 1

Related Questions