两个SQL COUNT()查询?
发布时间:2021-01-14 06:14:30 所属栏目:MsSql教程 来源:网络整理
导读:我想计算表中记录的总数,以及匹配特定条件的记录总数.我可以通过两个单独的查询执行这些操作 SELECT COUNT(*) AS TotalCount FROM MyTable;SELECT COUNT(*) AS QualifiedCount FROM MyTable {possible JOIN(s) as well e.g. JOIN MyOtherTable mot ON MyTable
我想计算表中记录的总数,以及匹配特定条件的记录总数.我可以通过两个单独的查询执行这些操作 SELECT COUNT(*) AS TotalCount FROM MyTable; SELECT COUNT(*) AS QualifiedCount FROM MyTable {possible JOIN(s) as well e.g. JOIN MyOtherTable mot ON MyTable.id=mot.id} WHERE {conditions}; 有没有办法将这些组合成一个查询,以便我在一行中得到两个字段? SELECT {something} AS TotalCount,{something else} AS QualifiedCount FROM MyTable {possible JOIN(s)} WHERE {some conditions} 如果没有,我可以发出两个查询并将它们包装在一个事务中,这样它们就是一致的,但我希望能用一个查询. 编辑:我最关心原子性;如果有两个子SELECT语句需要,只要有来自某个地方的INSERT,它就不会使两个响应不一致. 编辑2:CASE答案是有帮助的,但在我的具体实例中,条件可能包括与另一个表的JOIN(忘了在我的原始帖子中提到,抱歉)所以我猜这种方法不起作用. 解决方法一种方法是将表加入自身:select count(*) as TotalCount,count(s.id) as QualifiedCount from MyTable a left join MyTable s on s.id = a.id and {some conditions} 另一种方法是使用子查询: select (select count(*) from Mytable) as TotalCount,(select count(*) from Mytable where {some conditions}) as QualifiedCount 或者你可以把条件放在一个案例中: select count(*) as TotalCount,sum(case when {some conditions} then 1 else 0 end) as QualifiedCount from MyTable 有关: SQL Combining several SELECT results (编辑:西双版纳站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |