连接两个表时的sql查询

6kkfgxo0  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(378)

我需要在sql中连接两个表,并且我需要找到表a中有多少客户id也在表b中找到,提取表b中每年也购买了多少客户id。我的问题如下:

SELECT
  a.year, count(distinct(a.id), 
  count (distinct(b.id)
FROM
  purchase as A, 
  purchase2 as B
WHERE 
  (a.id=b.id) 
  AND 
  a.year>2010
GROUP BY a.year

是这样吗?我需要在select语句中包含count(distinct(b.id))吗?我是否也需要按b.year分组?
提前感谢您的帮助

kyvafyod

kyvafyod1#

更改distinct,可以进行内部联接以确保:

SELECT
  A.year, 
  count(DISTINCT A.id), 
  count (DISTINCT B.id)
FROM
  purchase as A 
  INNER JOIN purchase2 B ON B.id = A.id
WHERE 
  A.year>2010
GROUP BY 
  A.year,
  B.year
ruoxqz4g

ruoxqz4g2#

我想 union all 聚合是最好的方法。从每个id/年的信息开始:

select id, year, max(in_a), max(in_b)
from ((select distinct id, year, 1 as in_a, 0 as in_b
       from purchase
      ) union all
      (select distinct id, year, 0 as in_a, 1 as in_b
       from purchase2
      ) 
     ) ab
group by id, year;

然后按年度汇总:

select year,
       sum(in_a) as total_a,
       sum(in_b) as total_b,
      sum(in_a * in_b) as in_both
from (select id, year, max(in_a), max(in_b)
      from ((select distinct id, year, 1 as in_a, 0 as in_b
             from purchase
            ) union all
            (select distinct id, year, 0 as in_a, 1 as in_b
             from purchase2
            ) 
           ) ab
      group by id, year
     ) iy
group by year;

相关问题