![](/img/trans.png)
[英]count date per month , per year on database with date format with CodeIgniter
[英]Count totals per month per salesman
我有一个带有订单的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循环中查询每个推销员的结果,该结果会生成我已经拥有的表。
当前查询亩为:
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一起使用
您可以使用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;
这将只放置各个月份的摘要行,而不是年份和月份的摘要行。
没有看到您的节目创建表,很难给您确切的查询。 通俗地说,我喜欢用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;
让数据库完成所有工作,这是您擅长的。 (并填补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;
如果真的没有提供年份总计,请进行调整。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.