【问题标题】:SQL Join with a group by tableSQL Join 按表分组
【发布时间】:2021-07-11 00:35:14
【问题描述】:

您好,我需要您的帮助:

表 A 每次员工联系公司时都会有一行

ID Name Company Industry Segment Date Manager
1 John XYZ Services Corp 2021-03-01 Peter
2 John ABC Manufacturing Corp 2021-03-01 Peter
3 Rachel DEF Services MidMarket 2021-03-05 Maria

表 B 的每月目标是每个行业和细分的“覆盖率”或“计数 ID”:

Industry Segment Month and Year Target Companies Target Count ID
Manufacturing Corp 2021-03-01 100 15
Manufacturing MidMarket 2021-03-01 120 20
Services Corp 2021-03-01 80 10
Services MidMarket 2021-03-01 95 35

现在我正在加入这两个表,以按月查看目标与实际情况,如下所示:

**Temporary Table**
Select
'Industry', 
'Segment', 
LAST_DAY(('Date') - INTERVAL 1 MONTH) + INTERVAL 1 DAY AS 'Month and Year',
Count ('ID') as 'a.Count_ID',
Count (Distinct ('Company') as 'a.Count_Company'
From Table A
Group by
1,2
Select
'a.Industry', 
'a.Segment', 
'a.Month and Year',
'a.Count_ID',
'a.Count_Company',
'b.Target Companies',
'b.Target Count ID'
From temporary table as a Left Join Table B as b
ON 'a.Industry' = 'b.Industry'
AND a.Segment = 'b.Segment'
AND a.Month and Year' = 'b.Month and Year'

现在我还需要在输出中添加经理和员工姓名,但目标没有按员工和经理拆分。有没有办法在没有 group by 的情况下加入这 2 个表?

【问题讨论】:

  • 编辑您的问题并显示您想要的结果。
  • 默认情况下,(几乎)MySQL 中引号中的任何内容都是字符串。

标签: mysql sql join group-by


【解决方案1】:

加入前聚合。因为可以有多个员工和经理,我建议使用group_concat()

select b.*, a.num_companies, a.num_contacts, a.names, a.managers
from b join
     (select date + (1 - day(date)) day as year_month,
             industry, segment,
             count(distinct company) as num_companies,
             count(*) as num_contacts,
             group_concat(distinct name) as names,
             group_concat(distinct manager) as managers
      from a
      group by year_month, industry, segment
     ) a
     on a.industry = b.industry and a.segment = b.segment and
        a.year_month = b.year_month

【讨论】:

    猜你喜欢
    • 2022-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 2019-09-13
    • 2021-12-23
    相关资源
    最近更新 更多