我的表设置基本上是这样的:
Question | Category
=========|=========
Who? |Vague
What? |Vague
When? |Specific
Why? |Specific
How? |Specific
我想选择所有问题,但我还想返回与当前正在选择的条目属于同一类别的条目数量,如下所示:
Question | Category | Count
=========|==========|======
Who? |Vague |2
What? |Vague |2
When? |Specific |3
Why? |Specific |3
How? |Specific |3
我该怎么做?
答案 0 :(得分:4)
在Oracle(以及大多数其他数据库)中,您只需使用分析函数:
select t.*, count(*) over (partition by category) as cnt
from t;
在MySQL中,相关子查询可能是最好的方法:
select t.*, (select count(*) from t t2 where t2.category = t.category) as cnt
from t;
答案 1 :(得分:1)
Select a.Question, a.Category, count(*)
From table a
join table b
on b.Category = a.Category
Group By a.Question, a.Category