SQL:使用不同的表计数(*)和groupby

时间:2014-04-21 06:05:37

标签: sql sqlite

我有两张桌子,如下所示。

第一张表tblCategory

enter image description here

第二张表tblWord

enter image description here

Required Output

enter image description here

输出时,

TotalCount count(*) group by categoryid来自tblWord

Played count(*) where isPlayed = 1 group by categoryid来自tblword

因此,为了从2表中获取结果,我尝试了以下查询错误。

select (select count(*) from tblwords group by categoryid) as count, (select count(*) from tblwords where isPlayed = 1 group by categoryid) as played, categoryID, categoryname from tblcategory

查询中有任何建议可以获得所需的输出或任何有用的链接吗?

3 个答案:

答案 0 :(得分:3)

获得总计数的确切输出

SELECT t.categoryID, t.name,
       COUNT(*) as TotalCount, SUM(isplayed) as Played
FROM tblCategory t
INNER JOIN tblWord tw
ON t.categoryID = tw.categoryID
GROUP BY t.categoryID, t.name

仅计算isPlayed = 1的计数

SELECT t.categoryID, t.name,
       COUNT(*) as TotalCount, SUM(isplayed) as Played
FROM tblCategory t
INNER JOIN tblWord tw
ON t.categoryID = tw.categoryID
WHERE isPlayed=1
GROUP BY t.categoryID, t.name

答案 1 :(得分:2)

试试这个

SELECT tw.Category_ID, tc.NAME,
       COUNT(*) AS TotalCount, SUM(tw.IsPlayed=1) AS Played ,SUM(tw.IsPlayed=0) AS NonPlayed
FROM Table_Category  tc
INNER JOIN Table_Word tw 
ON tc.Category_ID = tw.Category_ID 
-- WHERE tw.IsPlayed=1
GROUP BY tc.Category_ID, tc.NAME

这里使用SUM(tw.IsPlayed=1) AS Played ,SUM(tw.IsPlayed=0) AS NonPlayed,所以你会得到播放和非播放

答案 2 :(得分:0)

select *
from
(select categoryID, count(isPlayed), sum(isPlayed) from tblword group by categoryID) b
left join 
tblcategory a 
on a.categoryID = b.categoryID

我先聚合,然后加入。