这可能是一个简单的但我无法理解它。
我有一个MemberBusinessCats表,其中包含一个BusinessCatID和一个MemberID ..表格可以这样呈现:
+-----------------------+-----------------+------------+
| MemberBusinessCatID | BusinessCatID | MemberID |
+-----------------------+-----------------+------------+
| 27 | 45 | 102 |
+-----------------------+-----------------+------------+
| 28 | 55 | 102 |
+-----------------------+-----------------+------------+
| 29 | 61 | 102 |
+-----------------------+-----------------+------------+
| 30 | 45 | 33 |
+-----------------------+-----------------+------------+
| 31 | 23 | 33 |
+-----------------------+-----------------+------------+
| 32 | 45 | 73 |
+-----------------------+-----------------+------------+
| 32 | 61 | 73 |
+-----------------------+-----------------+------------+
| 32 | 45 | 73 |
+-----------------------+-----------------+------------+
如何制作脚本以显示以下数据
+-----------------+---------------------+
| BusinessCatID | NumMembers In Cat |
+-----------------+---------------------+
| 45 | 3 |
+-----------------+---------------------+
| 55 | 1 |
+-----------------+---------------------+
| 61 | 2 |
+-----------------+---------------------+
| 23 | 1 |
+-----------------+---------------------+
非常感谢提前。
neojakey
答案 0 :(得分:5)
您需要使用带GROUP BY
的聚合函数:
select BusinessCatID, count(*) NumMembersInCat
from MemberBusinessCats
group by BusinessCatID
也可以使用count() over()
:
select distinct BusinessCatID,
count(*) over(partition by BusinessCatID) NumMembersInCat
from MemberBusinessCats
如果您想计算每个类别中的成员数量,那么您可以使用:
select BusinessCatID,
count(distinct MemberID) NumMembersInCat
from MemberBusinessCats
group by BusinessCatID
答案 1 :(得分:4)
试试这个
select BusinessCatID ,count(BusinessCatID) as NumMembers_In_Cat
from MemberBusinessCats
group by BusinessCatID
答案 2 :(得分:2)
基于您拥有BusinessCatID&amp ;;会员ID(45,73)列出两次,但只在您需要COUNT(DISTINCT x)时计算
SELECT BusinessCatID, COUNT(DISTINCT MemberID) as NumMembersInCat
FROM MemberBusinessCatID
GROUP BY BusinessCatID
这将计算每个BusinessCatID的不同成员(基于MemberID)。如果您不担心重复,那么使用COUNT(MemberID)甚至COUNT(1)将正常工作。
答案 3 :(得分:1)
试试这个(或类似的东西):
select BusinessCatID ,count(*) as NumMembersInCat
from MemberBusinessCats
group by BusinessCatID
答案 4 :(得分:0)
试试这个
select BusinessCatID, COUNT(BusinessCatID)
from MemberBusinessCatID
group by BusinessCatID
答案 5 :(得分:0)
Select BusinessCatID, count(MemberID) as [NumMembers In Cat]
from MemberBusinessCats
group by BusinessCatID, MemberID
答案 6 :(得分:0)
我理解这个问题来自不同的TRIPLE(MemberBusinessCATID,BusinessCATID,MemberID),总结了BusinessCATID。在这种情况下,查看不同的三元组或双元组是相同的,但在更大的数据集中可能会有所不同:
创建了一个视图:
create view dist_catView as
SELECT distinct MemberBusinessCATID, BusinessCATID, Member ID from cat_table
然后
SELECT BusinessCATID, count(MemberID) from dist_catView
group by BusinessCATID