正确聚合带有子查询的查询

时间:2018-10-28 16:47:41

标签: mysql subquery

我正在处理一个MySQL查询,该查询带有一系列日期的子查询。当我对其中一个日期(pulldate>'2018-09')使用过滤器时,结果按预期工作:

SELECT t1.`pulldate`,
SUM(t1.cost_by_item) AS total_cost,
ROUND((t2.total_cost_score / SUM(t1.cost_by_item)), 2) AS cost_utilization_percent_inv,
1-(ROUND((t2.total_cost_score / SUM(t1.cost_by_item)), 2)) AS cost_utilization_percent,
(t2.total_cost_score) AS cost_score_all
FROM
(SELECT pulldate,
    f.redefined_item_type,
    f.group,
    COUNT(f.name),
    ((COUNT(f.name) * e.estimated_item_cost))/1000000 AS cost_by_item
FROM item_summary f
JOIN est_item_cost e ON f.redefined_item_type = e.item_type
WHERE f.group != '' AND pulldate > '2018-09'
GROUP BY f.redefined_item_type) AS t1,
(SELECT ROUND(sum(cost_score)) AS total_cost_score
FROM item_summary
WHERE days_of_data > 30 AND group != '' AND pulldate > '2018-09') AS t2;

但是当我尝试删除数据过滤器并尝试不同类型的聚合时,我没有为pulldate的每个值(即按pulldate分组)都获得一行。我取而代之的是把它们看起来都一样。

SELECT t1.`pulldate`,
SUM(t1.cost_by_item) AS total_cost,
ROUND((t2.total_cost_score / SUM(t1.cost_by_item)), 2) AS cost_utilization_percent_inv,
1-(ROUND((t2.total_cost_score / SUM(t1.cost_by_item)), 2)) AS cost_utilization_percent,
(t2.total_cost_score) AS cost_score_all
FROM
(SELECT pulldate,
    f.redefined_item_type,
    f.group,
    COUNT(f.name),
    ((COUNT(f.name) * e.estimated_item_cost))/1000000 AS cost_by_item
FROM item_summary f
JOIN est_item_cost e ON f.redefined_item_type = e.item_type
WHERE f.group != ''
GROUP BY f.redefined_item_type) AS t1,
(SELECT ROUND(sum(cost_score)) AS total_cost_score
FROM item_summary
WHERE days_of_data > 30 AND group != '') AS t2
GROUP BY t1.`pulldate`;

我确定我只是找不到合适的位置进行聚合,因此,任何发现的帮助将不胜感激!

0 个答案:

没有答案