简体   繁体   中英

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 :)

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: 在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM