【问题标题】:SQL query when joining two tables连接两个表时的 SQL 查询
【发布时间】:2020-11-10 23:21:41
【问题描述】:

我需要在 SQL 中连接两个表,并且我需要在表 B 中找到表 A 中的多少个客户 ID 的计数,提取 A 中的多少个客户 ID 在表 B 中也按年购买。我的查询如下:

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 分组吗?

提前感谢您的帮助

【问题讨论】:

  • 与您的问题无关,但是:distinct 不是函数。将 distinct 关键字后面的列括在括号中不会改变任何内容 distinct (a)distinct a 相同
  • 请提供样本数据和期望的结果。

标签: sql


【解决方案1】:

改变你的不同,你可以做一个内部连接来确定:

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

【讨论】:

  • 感谢您的快速回复,当我以这种方式查询时,我没有按年份获得总数,不确定它在做什么,但例如 2017 在我定义 a.year=2017 时显示 31 个计数
【解决方案2】:

我认为union all 和聚合是最好的方法。从每个 id/year 的信息开始:​​

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;
  

【讨论】:

    猜你喜欢
    • 2016-05-27
    • 2017-07-05
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多