我有两张桌子,如下所示。
第一张表tblCategory
第二张表tblWord
Required Output
输出时,
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
查询中有任何建议可以获得所需的输出或任何有用的链接吗?
答案 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
我先聚合,然后加入。