SQL Oracle - 将多个计数作为一个查询返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6356564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 10:59:29  来源:igfitidea点击:

Oracle - return multiple counts as one query

sqloracle

提问by Raoul

I have a couple of queries, detailed below. I'd like to be able to run one SQL query which returns both counts, is this possible?

我有几个疑问,详情如下。我希望能够运行一个返回两个计数的 SQL 查询,这可能吗?

1.

1.

select nvl(count(rowid), 0) from tablename where OPP = 'FOO' and date = 'BAZ';

2.

2.

select nvl(count(rowid), 0) from tablename where OPP = 'BAR' and date = 'BAZ';

I've only found MSSQL specific solutions in my searches so far.

到目前为止,我只在搜索中找到了 MSSQL 特定的解决方案。

采纳答案by álvaro González

If you need them in a single row:

如果您在一行中需要它们:

SELECT
    COUNT(CASE OPP WHEN 'FOO' THEN 1 END),
    COUNT(CASE OPP WHEN 'BAR' THEN 1 END)
FROM tablename
WHERE OPP IN ('FOO', 'BAR') AND date = 'BAZ'

(The GROUP BY approach by Thilo is a better generic solution anyway.)

(无论如何,Thilo 的 GROUP BY 方法是更好的通用解决方案。)

Edit:I've removed NVL(). I had forgotten why I never use it.

编辑:我已经删除了NVL(). 我已经忘记了为什么我从不使用它。

回答by Thilo

If the condition really looks like that (same table, only one field different in the groups):

如果条件确实如此(同一张表,组中只有一个字段不同):

select opp, count(*) from tablename
where date = 'BAZ'
group by opp
having opp in ('FOO', 'BAR');

For arbitrary queries:

对于任意查询:

select 'A', count(*) from tableA
union all
select 'B', count(*) from tableB

回答by Denis de Bernardy

You could use a with statement:

您可以使用 with 语句:

with
count1 as (
select ...
),
count2 as (
select ...
)
select tot1, tot2
from count1, count2