我试图在Laravel应用中整理一个SQL查询,以创建客户,代理商和订单的报告,并需要一些帮助。
我已经说明了我的数据库表并从下面的模式中排除了不必要的字段:
CUSTOMERS TABLE
---------------------------------------------
cust_id cust_name
---------------------------------------------
1 Joe
2 Allan
3 Rick
4 Bill
代理商表
每个代理都通过cust_id外键与客户相关:
---------------------------------------------
agent_id agent_name cust_id
---------------------------------------------
1 Mike 2
2 Arnold 4
3 Lucy 1
4 Tom 3
ORDERS TABLE
订单表包含客户订单(由外键通过cust_id引用),包括订单日期和金额:
-----------------------------------------------
ord_id cust_id date amount
-----------------------------------------------
1 1 1/1/2001 50.00
2 1 1/1/2001 20.00
3 2 2/1/2001 20.00
4 4 2/1/2001 30.00
5 3 2/1/2001 75.00
6 3 3/1/2001 35.00
7 1 4/1/2001 20.00
8 3 5/1/2001 75.00
9 2 5/1/2001 10.00
期望的查询结果:
我想构建一个查询来检索每个客户的代理商名称,最近的销售日期,最近的销售金额和总销售额(按客户名称排序):
------------------------------------------------------------------
custName agentName LastSaleDate LastSaleAmt TotalSales
------------------------------------------------------------------
Allan Mike 10.00 5/1/2001 30.00
Bill Arnold 30.00 2/1/2001 30.00
Joe Lucy 20.00 4/1/2001 90.00
Rick Tom 75.00 5/1/2001 185.00
现状:
到目前为止,我已经创建了所有laravel模型并设置了雄辩的关系,但怀疑上面的查询应该使用常规SQL而不是ORM来完成。
使用SQL,我可以检索客户名称,代理商名称和总销售额,但不能检索上次销售日期和上次销售额:
SELECT customers.name, agents.name, SUM(orders.amount) FROM customers
LEFT JOIN agents
ON customers.id=agents.cust_id
LEFT JOIN orders
ON customers.id=orders.cust_id
GROUP BY customers.id, agents.name
ORDER BY customers.name ASC
如何扩展此查询以包含最近的销售日期和金额?
感谢任何帮助!
答案 0 :(得分:0)
想法是汇总以获得总销售日期和最后一个销售日期。然后加入orders
信息以获取最后一笔金额:
select oca.name, oca.agentname, oca.sales, oca.lastSaleDate,
o.amount as lastSaleAmount
from (select c.id, c.name, a.name as agentname, sum(o.amount) as sales,
max(o.date) as lastSaleDate
from orders o join
customers c
on o.cust_id = c.id join
agents a
on c.id = a.cust_id
group by c.id, c.name, a.name
) oca join
orders o
on o.cust_id = oca.cust_id and oca.lastSaleDate = o.date