2014-04-21 41 views
1

我有两个表,如下所示。SQL:计数(*)和groupby与不同的表

第一表tblCategory

enter image description here

第二表tblWord

enter image description here

Required Output

enter image description here

在输出时,

TotalCountcount(*)group by categoryidtblWord

Playedcount(*)where isPlayed = 1 group by categoryidtblword

所以从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

为了得到精确的输出与总数

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 
+0

@m哈桑我们可以通过上面的查询只得到isPlayed = 1点的记录? – Giri

+0

添加WHERE条件...检查编辑 –

+0

@mhasan:isPlayed是bool ...但我真的很惊讶我们可以应用sum()。有确切的输出。并学到新的东西“总和”:) – Devang

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

我第一次聚集,然后再加入。

+0

@milkey我们可以通过使用上面的查询得到只有isPlayed = 1记录吗? – Giri

+0

@Giri sum(isPlayed)表示isPlayed = 1记录的“计数”。如果你愿意,你也可以将它添加到内部select的where子句中,但是然后count和sum会给你相同的值。 – mikey

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被使用,那么你也会得到既起到和非打