我正在尝试按日期分组2个不同的表格。但是,由于我无法按日期分组,因此出现了问题。
我有2个表第一个“预算”和第二个“按地区划分的销售业绩” 该想法是显示所有月份(12个月)的预算 每个月我们都有数据,我们会看到每个特定月份的销售额。
SELECT
BB.RG,
BB.YEAR,
DATE_FORMAT( BB.MONTH, '%M' ) AS `MONTH`,
SPR.Bookings,
SPR.`Bookings PY`,
SPR.Billing,
SPR.`Billing PY`,
SPR.`GP Amt`,
SPR.`GP Amt PY`,
SUM( BB.BUDGET ) AS BUDGET
FROM
BRANCH_BUDGET BB
LEFT JOIN Sales_Performance_Region SPR
ON BB.MONTH = SPR.MONTH
WHERE
BB.RG = 'FE'
AND SPR.RG = 'FE'
AND BB.YEAR = '2018'
GROUP BY
BB.MONTH
上面你可以看到代码。由于我只有2个月的数据显示1月和2月,而不是显示12个月。
我希望这个问题有道理。你能指导我吗?
答案 0 :(得分:0)
每当您在GROUP BY
声明或WHERE
声明you will need to treat everything inside the select statement as an aggregate中的任何其他汇总函数后调用SELECT
时,您将面临问题:
在您的代码中:
SELECT `BRANCH_BUDGET`.`RG` ,
`BRANCH_BUDGET`.`YEAR` AS `YEAR` ,
`DATE_FORMAT( `BRANCH_BUDGET`.`MONTH` , '%M' ) AS `MONTH` ,
`Sales_Performance_Region`.`Bookings` ,
`Sales_Performance_Region`.`Bookings PY` ,
`Sales_Performance_Region`.`Billing` ,
`Sales_Performance_Region`.`Billing PY` ,
`Sales_Performance_Region`.`GP Amt` ,
`Sales_Performance_Region`.`GP Amt PY` ,
SUM( `BRANCH_BUDGET`.`BUDGET` ) AS `BUDGET`
FROM (
`BRANCH_BUDGET`
LEFT JOIN `Sales_Performance_Region` ON ( `BRANCH_BUDGET`.`MONTH` =
`Sales_Performance_Region`.`MONTH` )
)
WHERE `BRANCH_BUDGET`.`RG` = 'FE'
AND `Sales_Performance_Region`.`RG` = 'FE'
AND `BRANCH_BUDGET`.`YEAR` = '2018'
GROUP BY `BRANCH_BUDGET`.`MONTH`
您只能按BRANCH_BUDGET.MONTH
分组,但不要按任何其他列分组或在任何其他列上执行聚合功能(保存BRANCH_BUDGET.BUDGET
)。因此,您的输出有问题,因为它只返回两个月。
答案 1 :(得分:0)
首先感谢我想发布结果的评论以防有人感兴趣。
问题是:我没有从两个表加入Region(RG)。所以结果应该类似于下面的代码:
SELECT `BRANCH_BUDGET`.`RG` ,
`BRANCH_BUDGET`.`YEAR` AS `YEAR` ,
DATE_FORMAT( `BRANCH_BUDGET`.`MONTH` , '%M' ) AS `MONTH` ,
`Sales_Performance_Region`.`Bookings` ,
`Sales_Performance_Region`.`Bookings PY` ,
`Sales_Performance_Region`.`Billing` ,
`Sales_Performance_Region`.`Billing PY` ,
`Sales_Performance_Region`.`GP Amt` ,
`Sales_Performance_Region`.`GP Amt PY` ,
SUM( `BRANCH_BUDGET`.`BUDGET` ) AS `BUDGET`
FROM (
`BRANCH_BUDGET`
LEFT JOIN `Sales_Performance_Region`
ON ( `Sales_Performance_Region`.`MONTH` = `BRANCH_BUDGET`.`MONTH` )
AND ( `Sales_Performance_Region`.`RG` = `BRANCH_BUDGET`.`RG` )
)
WHERE `BRANCH_BUDGET`.`RG` = 'FE'
AND `BRANCH_BUDGET`.`YEAR` = '2018'
GROUP BY `BRANCH_BUDGET`.`MONTH`