假设我有这个查询
select
count(customerid) as Count_Own,
(select count(customerid) from Customers) Count_ALL
from
Customers
where
EmployeeID = 1
它显示了第一列中employeeid = 1和第二列中所有员工的客户数。
现在我想通过代替表Customers
来编写类似的查询,我有大的子查询:
select
count(customerid) as Count_Own,
(select count(customerid) from /*BIG QUERY*/) Count_ALL
from
( /*BIG QUERY*/ )
where
EmployeeID = 1
我现在对列Count_ALL
有一个问题,因为我想快速计算,而不使用我的子查询。我想知道它是否只是它的解决方案。
解决方法:创建一个假列以加入两个查询:
select
count(T1.customerid) as Count_Own, T2.Count_ALL
From ( Select 1 as joinField, --BIG QUERY-- ) T1
join (select count(customerid) Count_ALL, 1 as joinField
from customers) T2
on T1.joinField = T2.joinField
where T1.EmployeeID = 1
编辑到期OP评论。
您可以使用CTE避免两次写大查询。让我们使用这个简化的架构:
dh4@GLOW:~/tmp$ sqlite3 pepe.sql
SQLite version 3.11.0 2016-02-15 17:29:24
Enter ".help" for usage hints.
sqlite> create table t ( i int , e int );
sqlite> insert into t values
...> ( 1,1),
...> ( 2,1),
...> ( 3,1),
...> ( 1,2);
然后,您的查询是:
sqlite> with big_query as
...> ( select i,e from t )
...> select count(i), (select count(*) from big_query)
...> from big_query
...> where e=1;
3|4
你也可以使用假连接旅行来避免代理子查询:
sqlite> with big_query as
...> ( select i,e from t ),
...> q1 as
...> ( select count(*) as n, 1 as fake from big_query ),
...> q2 as
...> ( select count(*) as n, 1 as fake from big_query where e=1)
...> select q2.n, q1.n
...> from q1 inner join q2
...> on q1.fake=q2.fake;
3|4
最后一种方法是使用case
:
sqlite> select count( case when e = 1 then 1 else null end) , count(*)
...> from t
...> ;
3|4