【发布时间】:2017-06-17 14:03:51
【问题描述】:
我有一个相对复杂的查询,其中包含一些我用来为我的销售代表创建“排行榜”的子查询。问题是主要数据是通过 Sale_Date 过滤的,而我需要通过 Install_Date 过滤其中一列(只有 Installs 列)。我正在使用 MySQL 工作台和第 3 方商业智能平台以一种可展示的方式输出数据。下面是我目前正在做的事情的简化版本,但它显然不起作用或没有给我想要的东西。
select `Rep`, `Sales`, `Passed Credit`, `Sales Scheduled`, Installs
from
(select Rep_Name as `Rep`, count(*) as `Sales`..., count(...) as `Sales Scheduled`
from ss.customers
left join ss.users
on customers.rep_id = users.id
where Sale_Date between curdate() - interval 6 day and curdate()
group by Rep_Name with rollup) cust,
(select Rep_Name, count(*) as `Installs`
from ss.customers
left join ss.installs
on customers.id = installs.id
left join ss.users
on customers.rep_id = users.id
where Install_Date between curdate() - interval 6 day and curdate()
group by Rep_Name) inst
order by `Sales` desc, `Passed Credit` desc, ..., `Installs` desc
我得到的输出对于第一个表“cust”中的所有字段都是正确的,但我的所有代表都显示在查询的后半部分返回的第一个“安装”计数,无论是 1 还是 20。
它返回的是这样的:
Rep ----- Sales ----- Passed Credit ----- Sales Scheduled ----- Installs
John | 10 | 7 | 6 | 5
Mike | 8 | 7 | 6 | 5
Trey | 8 | 6 | 4 | 5
Drew | 6 | 3 | 3 | 5
Angel | 3 | 2 | 4 | 5
Total | 35 | 25 | 23 | 22
安装表还包括一些本周没有销售的人,但他们也没有出现在这里,他们应该出现的。理想情况下,表格应该是这样的:
Rep ----- Sales ----- Passed Credit ----- Sales Scheduled ----- Installs
John | 10 | 7 | 6 | 5
Mike | 8 | 7 | 6 | 9
Trey | 8 | 6 | 4 | 4
Drew | 6 | 3 | 3 | 4
Angel | 3 | 2 | 4 | 0
Tracy | 0 | 0 | 0 | 3
Diego | 0 | 0 | 0 | 1
Total | 35 | 25 | 23 | 26
我尝试了一些疯狂的连接、联合和 where 语句的组合。关于如何获得这个的任何其他想法?任何帮助表示赞赏!
更新 1 感谢 spencer7593,我能够通过使用左连接解决我的“安装”列显示不正确的问题。目前仍在努力显示本周销售额为 0 的代表,但有安装量(来自前几周的销售额)。
我之前忘记包含的所列表格的必要限定字段:
Customers - rep_id, Sale_Date, id, Passed_Credit, Sale_Scheduled
Users - id (which is customers.rep_id), Rep_Name, Rep_Office_Location
Installs - id (which is customers.id), Install_Date, Install_Status
我知道我们的 CRM 数据库是一团糟,不同表上的多个同名列代表不同的事物。它不是我设计的,同时也是我必须忍受的。
【问题讨论】:
标签: mysql join subquery left-join union