我已尝试过以下查询,但遗憾的是他们没有工作:(。 值得一提的是每个客户都有多个CustomerUsers
select (a.TotalJobs / b.DaysActive) from
(select count(jr.id) as TotalJobs
from jobrequests jr, customers c, customerusers cu
where jr.customeruserid=cu.id
and cu.customerid=c.id
group by c.name) as a,
(select datediff(curdate(), from_unixtime(c.CreationTime)) as DaysActive
from customers c
group by c.name) as b
请参见下表
Jobs: +----+--------------+ | ID | JobRequestID | +----+--------------+ | 1 | 1 | | 2 | 1 | | 3 | 1 | | 4 | 1 | | 5 | 1 | | 6 | 2 | | 7 | 2 | | 8 | 3 | | 9 | 3 | | 10 | 3 | | 11 | 4 | | 12 | 4 | | 13 | 5 | | 14 | 5 | | 15 | 6 | | 16 | 7 | | 17 | 8 | | 18 | 8 | | 19 | 9 | | 20 | 10 | +----+--------------+ JobRequests: +----+---------------+ | ID | CustomeUserID | +----+---------------+ | 1 | 1 | | 2 | 1 | | 3 | 2 | | 4 | 2 | | 5 | 2 | | 6 | 3 | | 7 | 4 | | 8 | 4 | | 9 | 4 | | 10 | 5 | | 11 | 5 | | 12 | 5 | | 13 | 6 | | 14 | 6 | | 15 | 7 | +----+---------------+ CustomerUsers: +----+------------+ | ID | CustomerID | +----+------------+ | 1 | 1 | | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 2 | | 6 | 2 | | 7 | 2 | | 8 | 3 | | 9 | 3 | | 10 | 4 | +----+------------+ Customers: +----+------+--------------+ | ID | Name | CreationTime | +----+------+--------------+ | 1 | a | 1415814194 | | 2 | b | 1415814194 | | 3 | c | 1415986994 | | 4 | d | 1415986994 | +----+------+--------------+
目前它返回16个结果(4X4),将每个结果从第一个子查询除以第二个每个结果(每个子查询返回4个结果)。任何人都可以帮我解决这个问题,将子查询1的1个结果除以子查询2中的对应者吗?
提前谢谢。
答案 0 :(得分:1)
我怀疑你可以做这样的查询:
select c.name, count(*) / (datediff(curdate(), from_unixtime(c.CreationTime))
from customerusers cu join
jobrequests jr
on jr.customeruserid = cu.id join
customers c
on cu.customerid = c.id
group by c.name;
我不明白为什么你需要两个子查询。
答案 1 :(得分:0)
我猜你需要join
你的结果 - 正如目前所写,你正在制作一个cartesian product
。
尝试这样的方法将c.id
添加到每个子查询中(最好将其按名称分组,而不是名称):
select (a.TotalJobs / b.DaysActive)
from (
select c.id,
count(jr.id) as TotalJobs
from jobrequests jr
join customers c on jr.customeruserid=cu.id
join customerusers cu on cu.customerid=c.id
group by c.id) a join (
select c.id,
datediff(curdate(), from_unixtime(c.CreationTime)) as DaysActive
from customers c
group by c.id) b on a.id = b.id
请注意,我已更新您的语法以使用更标准的join
语法。