计算子查询返回的行数

时间:2014-03-18 02:58:02

标签: sql

我们说这个名为tblsample

的表格

enter image description here

我试图获得每个codes唯一的title个数。因此,结果应为abc = 3def = 3

我现在的查询是

Select T1.title, COUNT(tbl2.code) as [No. of Codes]
from (Select t2.title, T2.CODE from tblsample as T2 where T2.category = 'com' group by t2.title, t2.CODE) AS tbl2
inner join tblsample as T1 on (T1.title = tbl2.title)
where T1.category = 'COM'
group by T1.title
order by T1.title

但是它正在返回abc = 15def = 9,所以我很困惑。我在哪里错了?

1 个答案:

答案 0 :(得分:2)

我认为查询就像这样简单:

Select title, COUNT(DISTINCT code) as [No. of Codes]
from tblsample 
where category = 'COM'
group by title
order by title