我有一个带有订单的mySQL表。每个表行包括订单日期,金额和销售人员
order_id |
amount |
saleman_id |
order_date
我想查询它,这样我就可以生成一个带有报告的HTML表格。
Year | Month | Total | Total for salesman 1 | Total for salesman 2 | etc...
2014 | 10 | 5000 | 2000 | 3000 | etc...
2014 | 11 | 6000 | 5000 | 1000 | etc...
这已经部分有效了,这意味着我有一个查询,允许我创建一个报告,显示所有销售人员每个月的总数,但我想知道是否有办法实现我想要的在单个SQL查询中,如果值得,那么性能就可以了。否则,我可以在PHP while循环中查询每个销售人员的结果,该循环生成我已经拥有的表。
Mu当前查询是:
SELECT
YEAR(ord_date) AS year,
MONTH(ord_date) AS month,
ROUND(SUM(...colum calculations...),2) AS sales,
COUNT(o.ord_id) AS count_orders
FROM
orders_ord AS o
GROUP BY
year, month
ORDER BY year DESC, month DESC;
我使用PHP 5.4和经典的mysql模块& mySQL5.5
答案 0 :(得分:2)
您可以使用with rollup
执行所需操作:
SELECT YEAR(ord_date) AS year, MONTH(ord_date) AS month, repid, MONTHNAME(ord_date) AS monthname,
ROUND(SUM(...colum calculations...),2) AS profit,
ROUND(SUM(...colum calculations...),2) AS sales,
COUNT(o.ord_id) AS count
FROM orders_ord o
GROUP BY year, month
ORDER BY year DESC, month desc, repid with rollup;
但是,由于汇总的性质,我建议在group by
中结合年份和月份:
SELECT YEAR(ord_date) AS year, MONTH(ord_date) AS month, repid, MONTHNAME(ord_date) AS monthname,
ROUND(SUM(...colum calculations...),2) AS profit,
ROUND(SUM(...colum calculations...),2) AS sales,
COUNT(o.ord_id) AS count
FROM orders_ord o
GROUP BY YEAR(ord_date) * 100 + MONTH(ord_date) desc, repid with rollup;
这将仅列出个别月份的摘要行,而不是年度和月份的摘要。
答案 1 :(得分:0)
如果没有看到您的show create table,很难给出确切的查询。 Genarelly speeking我喜欢在SQL中完成所有工作而不是PHP。但是,如果您有一个数据网格,并且想要显示小计或总计,那么请使用PHP来添加行。
无论如何,这里有一些可以帮助你的查询
此查询将为您提供四舍五入的利润和四舍五入的销售额
SELECT
rep_id,
YEAR(ord_date) AS year,
MONTH(ord_date) AS month,
MONTHNAME(ord_date) AS monthname,
ROUND(SUM(...colum calculations...),2) AS profit,
ROUND(SUM(...colum calculations...),2) AS sales,
COUNT(o.ord_id) AS count
FROM
orders_ord AS o
GROUP BY rep_id, year, month
ORDER BY year DESC, month DESC;
答案 2 :(得分:0)
让数据库做到全部,擅长。 (并填补PHP的空白时,保存所有额外的数据库访问。)
SELECT
YEAR(ord_date) AS year,
MONTH(ord_date) AS month,
MONTHNAME(ord_date) AS monthname,
saleman_id,
ROUND(SUM(...colum calculations...),2) AS profit,
ROUND(SUM(...colum calculations...),2) AS sales,
COUNT(o.ord_id) AS count
FROM
orders_ord
GROUP BY year, month, saleman_id
UNION ALL
SELECT
YEAR(ord_date) AS year,
MONTH(ord_date) AS month,
MONTHNAME(ord_date) AS monthname,
'zzz Total zzz',
ROUND(SUM(...colum calculations...),2) AS profit,
ROUND(SUM(...colum calculations...),2) AS sales,
COUNT(o.ord_id) AS count
FROM
orders_ord
GROUP BY year, month
ORDER BY year DESC, month DESC;
如果真的不提供年度总数,需要调整。