我有两个表,如下所示。

第一表tblCategory

在此处输入图片说明

第二表tblWord

在此处输入图片说明

Required Output

在此处输入图片说明

在输出时,

TotalCountcount(*)group by categoryidtblWord

Playedcount(*)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

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

===============>>#1 票数: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

===============>>#2 票数: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 ,所以你会同时获得Played和Non Played

===============>>#3 票数:0

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

我先汇总,然后加入。

  ask by Devang translate from so

未解决问题?本站智能推荐: