我有几个问题,详情如下。我希望能够运行一个返回两个计数的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';
到目前为止,我只在搜索中找到了MSSQL特定的解决方案。
答案 0 :(得分:8)
如果您需要一行:
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'
(无论如何,Thilo的GROUP BY方法是更好的通用解决方案。)
修改:我已删除NVL()
。我忘记了为什么我从不使用它。
答案 1 :(得分:6)
如果条件真的如此(同一个表,组中只有一个字段不同):
select opp, count(*) from tablename
where date = 'BAZ'
group by opp
having opp in ('FOO', 'BAR');
对于任意查询:
select 'A', count(*) from tableA
union all
select 'B', count(*) from tableB
答案 2 :(得分:3)
您可以使用with语句:
with
count1 as (
select ...
),
count2 as (
select ...
)
select tot1, tot2
from count1, count2