在SQLITE中对来自同一个表的两个SELECT语句执行JOIN

时间:2016-05-06 03:47:31

标签: sqlite

这就是我在SQLITE中有一个示例表的方法

ID  NAME    AGE ADDRESS     SALARY
1   Paul    32  California  20000.0
2   Allen   25  Texas   15000.0
3   Teddy   23  Norway  20000.0
4   Mark    25  Rich-Mond   65000.0
5   David   27  Texas   85000.0
6   Kim 22  South-Hall  45000.0
7   Paul    32  California  20000.0
8   Allen   25  Texas   15000.0
9   Teddy   23  Norway  20000.0

我想要实现的是在我的SQLITE表上连接这两个查询

select AGE, count(*)  as SALARYLESSTHAN45 from company where salary < 45000 group by salary 

select AGE, count(*)  as SALARYMORETHAN45 from company where salary > 45000 group by salary 

我尝试了以下

select AGE, count(*)  as SALARYLESSTHAN45 from company where salary < 45000 group by salary  ) T1
INNER JOIN
select AGE, count(*)  as SALARYMORETHAN45 from company where salary > 45000 group by salary  ) T2
ON T1.AGE = T2.AGE

但无法让这个工作......

有人可以在SQLITE中分享如何实现这一目的的示例吗?

1 个答案:

答案 0 :(得分:0)

两个不同的表上的连接看起来像这样:

SELECT ... FROM Tab1 JOIN Tab2 ON ...

要对查询结果进行连接,必须使用子查询替换表名:

select AGE,
       SALARYLESSTHAN45,
       SALARYMORETHAN45
from (select AGE,
             count(*) as SALARYLESSTHAN45
      from company
      where salary < 45000
      group by salary)
join (select AGE,
             count(*) as SALARYMORETHAN45
      from company
      where salary > 45000
      group by salary)
using (AGE);