0

我是 sqlite 的新手。

我有 2 个具有完全相同架构的表(tableA、tableB)。

id | CAT | country

他们在特殊的软件版本上跟踪每个国家/地区的项目数量

我想创建一个查询来比较 tableA 和 tableB 上每个国家/地区的行数,其中 CAT = "AAA" 在单个结果上,例如:

COUNTRY |count_tableA |count_tableB|
ARG     |12           |16          |
BRA     |23           |33          |

我可以在单独的表格中实现它,但不能在单个表格中实现。单独的表示例:

select COUNTRY, count(*) as count_tableA from tableA WHERE CAT ="AAA" GROUP BY COUNTRY
select COUNTRY, count(*) as count_tableB from tableB WHERE CAT ="AAA" GROUP BY COUNTRY

谢谢您的帮助

4

2 回答 2

2

一种方法是UNION在 2 个表中使用条件聚合:

select country, 
       sum(tablename = 'a') count_tableA,
       sum(tablename = 'b') count_tableB
from (
  select 'a' tablename, id, cat, country from tableA
  union all
  select 'b' tablename, id, cat, country from tableB
)
where cat = 'AAA'
group by country
于 2020-10-14T14:24:33.030 回答
0

您可以使用WITHCOUNT

with t1 as (select country, count(*) as c1 from tableA where cat = 'AAA' group by country), 
t2 as (select country, count(*) as c1 from tableB where cat = 'AAA' group by country)
select a1.country, 
   ifnull((select t1.c1 from t1 where t1.country = a1.country), 0) as count_tableA, 
   ifnull((select t2.c1 from t2 where t2.country = a1.country), 0) as count_tableB from (
     select distinct country from tableA where cat = 'AAA'
     union
     select distinct country from tableB where cat = 'AAA'
   ) a1
group by country
于 2020-10-14T15:55:27.910 回答