简体   繁体   English

列中每个重复数字的SQL计数

[英]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. 我很困惑,因为我还想确保它在保持m_id值不同的同时对p_id进行计数。

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. 这是因为,如果您要计算与每个p_id相关联的不重复m_id的数量,如果只想计算表中p_id的数量,请删除distinct关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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