我有一个订单表,其中在评论记录中有订单创建者的名称。 有3个销售人员。我想从每个销售人员那里获取统计数据。 我想出了下面的查询输出一个人的订单,它工作正常,但我真的很难在一个选择查询中获取每个销售人员的订单并在同一个表中输出。我尝试了Union并在select中选择,但我想我正在构建错误的查询。以下工作正常输出亚当的订单(销售数量和该人的总销售额)。谢谢任何提示。
SELECT MONTHNAME(orders.despatched) as Month, YEAR(orders.despatched) as Year,
SUM(orders.price) as AdamSales, COUNT(orders.comment) as AdamQt FROM orders
WHERE
orders.comment LIKE '%Adam%' AND
orders.status = 'despatched' AND
orders.despatched BETWEEN '$d1' AND '$d2'
GROUP BY YEAR(orders.despatched), MONTH(orders.despatched)
order by orders.despatched ";
我知道,如果只有这个人的名字不是评论记录中的某个字符串,那么可能按人分组是最好的。
答案 0 :(得分:1)
您可以根据评论
对案例陈述进行分组SELECT
( case when ORDERs.comments LIKE '%Adam%' THEN 'Adam'
when ORDERS.comments LIKE '%Peter%' THEN 'Peter' END ) as 'Person'
MONTHNAME(orders.despatched) as Month,
YEAR(orders.despatched) as Year,
SUM(orders.price) as Sales,
COUNT(orders.comment) as Qt FROM orders
WHERE
(orders.comment LIKE '%Adam%' OR orders.comment LIKE '%Peter%' ) AND
orders.status = 'despatched' AND
orders.despatched BETWEEN '$d1' AND '$d2'
GROUP BY YEAR(orders.despatched), MONTH(orders.despatched),
( case when ORDERs.comments LIKE '%Adam%' THEN 'Adam'
when ORDERS.comments LIKE '%Peter%' THEN 'Peter' END )
order by orders.despatched
答案 1 :(得分:1)
如果这个人的名字只是一个字符串,那么你需要的是对一个Case表达式进行分组,该表达式将为第一个人返回1,为第二个人返回2,等等;类似的东西:
Group by Case When orders.comment LIKE '%Adam%' then 1 When ... End, ...
当然,真正的解决方案是为人员添加一个表并为其添加关系。