也许我的谷歌已关闭。
我有一张桌子:sub_transfer_jobs
job_date mo_id sub_quantity shift_id
2017-05-16 24581 12 1
2017-05-16 86122 8 2
etc.
另一张表:mo_numbers
mo_id customer
24581 cust1
86122 cust2
68515 cust1
etc.
我有另一张桌子:日历。
This just has a date value for every date
我需要得到的是每位客户每天的金额字符串列表
例如
2017-05-15 cust1 50
2017-05-15 cust2 0
2017-05-16 cust1 22
2017-05-16 cust2 10
etc
根据日期范围
,我将根据客户的情况获得一份明确的客户列表这是我的地方,但在子查询上有问题
SELECT `sub_transfer_jobs`.`sub_quantity`, `sub_transfer_jobs`.`job_date`, `sub_transfer_jobs`.`shift_id`, `mo_numbers`.`customer`
FROM `sub_transfer_jobs`
join mo_numbers on `mo_numbers`.`mo_id` = `sub_transfer_jobs`.`mo_id`
right join calendar on `calendar`.`datefield` = `sub_transfer_jobs`.`job_date`
right join (
select DISTINCT `mo_numbers`.`customer` from sub_transfer_jobs
join `mo_numbers` on `mo_numbers`.`mo_id` = `sub_transfer_jobs`.`mo_id`
where job_date > '2017-04-15'
) as customerList on customerList.customer = mo_numbers.customer
where job_date > '2017-04-15'
group by `mo_numbers`.`customer`, `sub_transfer_jobs`.`job_date`
编辑:更正sql以获得我需要的东西(按逗号分隔分组)
select basecustomer, GROUP_CONCAT(IFNULL(customerdaytotals.total, 0) ORDER BY datefield ASC) AS total FROM
(select basecustomer, datefield from
(select distinct `mo_numbers`.`customer` as basecustomer
FROM `sub_transfer_jobs`
JOIN `mo_numbers` on `mo_numbers`.`mo_id` = `sub_transfer_jobs`.`mo_id`
where `sub_transfer_jobs`.`job_date` > '2017-04-01') as used_customers
CROSS JOIN (
SELECT `calendar`.`datefield` from `calendar`
WHERE `calendar`.`datefield` > '2017-04-01' AND `calendar`.`datefield` < '2017-05-11'
) as daterange) as basedata
LEFT JOIN (
select `sub_transfer_jobs`.`job_date`, `mo_numbers`.`customer`, sum(`sub_transfer_jobs`.`sub_quantity`) as total
FROM `sub_transfer_jobs`
JOIN `mo_numbers` on `mo_numbers`.`mo_id` = `sub_transfer_jobs`.`mo_id`
GROUP BY `sub_transfer_jobs`.`job_date`, `mo_numbers`.`customer`
) as customerdaytotals on customerdaytotals.job_date = basedata.datefield and customerdaytotals.customer = basedata.basecustomer
GROUP BY basecustomer
这给出了
的结果cust1 0,1857,1262,1166,517,1551,0,0,1469,1670,400,0,0,0,...
cust2 0,123,7,0,7,0,0,0,0,0,0,0,0,0,0,84,70,9,53,3,0,0,4...
cust3 0,0,75,425,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0...
cust4 0,0,41,36,44,26,0,0,0,41,0,0,0,0,0,16,88,12,0,0,0,...
cust5 0,277,552,433,280,491,0,0,124,880,1269,0,0,0,0,495...
cust6 0,255,124,620,184,129,0,0,309,103,88,0,0,0,0,118,2...
cust7 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,...
cust8 0,209,123,15,84,296,0,0,296,15,262,0,0,0,0,301,200,...
答案 0 :(得分:2)
您需要使用CROSS JOIN
来获取客户和日期的所有组合。然后LEFT JOIN
使用查询获取每个客户每个日期的总数。
SELECT m.date, c.customer, IFNULL(t.total, 0) AS total
FROM mo_numbers AS m
CROSS JOIN customer AS c
LEFT JOIN (
SELECT date, mo_id, SUM(quantity) AS total
FROM mo_numbers
GROUP BY date, mo_id
) AS t ON m.mo_id = t.mo_id AND c.mo_id = t.mo_id