dtwxt88240 2014-09-29 20:27
浏览 1014

MySql复杂查询来统计每个人的订单

I have a table with orders in which in Comments record there is a name of the order creator. There is 3 sales people. I want to fetch statistics from each sales person. I came up with below query to output one person's orders and it works fine but I really struggle if it possible in one select query to fetch orders of each sales person and output in the same table. I tried Union and select within select but I guess I am constructing the query wrong. The below works fine to output just Adam's orders(Qty sold and total Sales value for that person).Thanks for any tips.

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 ";

I know that possibly grouping by Person would be best if only the person's name wasn't just a string somewhere inside Comment record.

  • 写回答

2条回答 默认 最新

  • dou11655853 2014-09-29 20:32
    关注

    you can do group by on the case statement based on the comments

    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 
    
    评论

报告相同问题?

悬赏问题

  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False