SELECT sum(monthly_target) as month_target
FROM `tbl_goal`
inner join user
on tbl_goal.uid=user.id where user.store=1 and month='February'
结果: month_target = 9000
SELECT
sum(net) as achieved,
sum(hairs_total) as hairs_total,
sum(beard_total) as beard_total,
sum(product_total) as product_total
FROM `data`
inner join user
on data.uid=user.id where user.store=1 and month='February'
结果:达到= 103 hairs_total = 63 beard_total = 40 product_total = 0
请给我任何提示如何将这些加入其中?
答案 0 :(得分:2)
棘手的一个。您当前的连接条件意味着您希望按用户聚合,但WHERE
子句清楚地表明您需要存储级聚合。因此,我们可以尝试重写您的查询以按商店聚合。下面两个子查询中的每一个都执行单独的聚合,通过连接将store
id引入用户表。然后,在外部我们将user
表连接到每个子查询。
SELECT
u.store,
COALESCE(t1.achieved, 0) AS achieved,
COALESCE(t1.hairs_total, 0) AS hairs_total,
COALESCE(t1.beard_total, 0) AS beard_total,
COALESCE(t1.product_total, 0) AS product_total,
COALESCE(t2.month_target 0) AS month_target
FROM user u
LEFT JOIN
(
SELECT
usr.store,
SUM(d.net) AS achieved,
SUM(d.hairs_total) AS hairs_total,
SUM(d.beard_total) AS beard_total,
SUM(d.product_total) AS product_total
FROM data d
INNER JOIN user usr
ON d.uid = usr.id
WHERE d.month = 'February'
GROUP BY usr.store
) t1
ON u.store = t1.store
LEFT JOIN
(
SELECT
usr.store,
SUM(t.monthly_target) AS month_target
FROM tbl_goal t
INNER JOIN user usr
ON t.uid = usr.id
WHERE t.month = 'February'
GROUP BY usr.store
) t2
ON u.store = t2.store;
WHERE
u.store = 1;
如果您想要所有商店的报告,只需删除外部WHERE
子句。
答案 1 :(得分:0)
SELECT
sum(monthly_target) as month_target,
sum(net) as achieved,
sum(hairs_total) as hairs_total,
sum(beard_total) as beard_total,
sum(product_total) as product_total
FROM
user
inner join `tbl_goal` on tbl_goal.uid = user.id
inner join `data` on data.uid = user.id
where
user.store = 1
and month = 'February'
答案 2 :(得分:0)
使用多个内部联接来实现此目的。 试试这个
SELECT sum(tbl_goal.monthly_target) as month_target, sum(data.net) as achieved,
sum(data.hairs_total) as hairs_total,
sum(data.beard_total) as beard_total,
sum(data.product_total) as product_total
FROM `tbl_goal`
inner join user
on tbl_goal.uid=user.id
inner join data on tbl_goal.uid=data.uid
where user.store=1 and data.month='February'