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.
select nvl(count(rowid), 0) from tablename where OPP = 'FOO' and date = 'BAZ';
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特定的解决方案。
3 个解决方案
#1
8
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()。我忘记了为什么我从不使用它。
#2
3
You could use a with statement:
你可以使用with语句:
with
count1 as (
select ...
),
count2 as (
select ...
)
select tot1, tot2
from count1, count2
#3
3
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
#1
8
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()。我忘记了为什么我从不使用它。
#2
3
You could use a with statement:
你可以使用with语句:
with
count1 as (
select ...
),
count2 as (
select ...
)
select tot1, tot2
from count1, count2
#3
3
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