SQL:Count(*)和groupby具有不同的表
我有两张表,如下所示 第一表TBL类别 第二表tblWord 所需输出 在产出方面 TotalCount是来自tblWord的按类别ID分组的计数* 播放的是count*,其中isPlayed=1组,按类别ID从tblword开始 所以为了从2表中得到结果,我尝试了以下错误的查询SQL:Count(*)和groupby具有不同的表,sql,sqlite,Sql,Sqlite,我有两张表,如下所示 第一表TBL类别 第二表tblWord 所需输出 在产出方面 TotalCount是来自tblWord的按类别ID分组的计数* 播放的是count*,其中isPlayed=1组,按类别ID从tblword开始 所以为了从2表中得到结果,我尝试了以下错误的查询 select (select count(*) from tblwords group by categoryid) as count, (select count(*) from tblwords where isP
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
查询中是否有获得所需输出或任何有用链接的建议?以获得总计数的准确输出
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
要获取仅显示为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
以获得具有总计数的精确输出
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
要获取仅显示为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
我先聚合,然后加入
我会先聚合,然后加入。试试这个
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
这里SUMtw.IsPlayed=1为播放状态,SUMtw.IsPlayed=0为非播放状态,因此您将同时获得播放和非播放状态
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
这里,SUMtw.IsPlayed=1作为播放,SUMtw.IsPlayed=0作为未播放,因此您将同时获得播放和未播放的记录@milkey我们可以使用上述查询仅获得IsPlayed=1条记录吗?@Giri sumisPlayed表示IsPlayed=1条记录的计数。如果愿意,您也可以将其添加到内部select上的where子句中,但count和sum将为您提供相同的值。@milkey使用上述查询只能获得isPlayed=1条记录吗?@Giri sumisPlayed表示isPlayed=1条记录的计数。如果愿意,您也可以将其添加到内部select上的where子句中,但count和sum将为您提供相同的值。@m hasan使用上述查询是否只能获得isPlayed=1记录?@mhasan:isPlayed is bool。。。但我真的很惊讶我们能应用sum。得到了精确的输出。并且学到了新的东西sum:@m hasan使用上面的查询只能得到isPlayed=1条记录吗?@mhasan:isPlayed是bool。。。但我真的很惊讶我们能应用sum。得到了精确的输出。并学到了新东西sum: