dongwen7187 2018-05-16 06:33
浏览 63
已采纳

左连接计数忽略左表列从计数

I have two tables ...first has order_id, order_status, and user_id .... second table has order_id ,and product_id, product_quantity like below

1st table

    order_id | order_status | user_id
    ----------------------------
    1        | 5            | 2
    2        | 1            | 1
    3        | 5            | 1
    4        | 5            | 1

2nd Table

order_id | product_id | quantity
----------------------------
1        | 200        | 4
2        | 201        | 2
2        | 200        | 1
2        | 207        | 4
3        | 201        | 1
3        | 200        | 6
4        | 201        | 8

I want to get

    user_id | Total_orders | quantity
    ----------------------------
    1       | 2            | 15
    2       | 1            | 4

get user_id where order_status = 5 and sum(quantity) group by user_id

MY TRY

SELECT h.user_id
     , COUNT(IF(h.order_status = 5,1,0)) AS total_orders
     , SUM(o.quantity) AS quantity 
  FROM table1 h 
  LEFT 
  JOIN table2 o  
    ON o.order_id = h.order_id 
 WHERE h.order_status = 5 
 GROUP 
    BY h.user_id

But, it gives me result counting all instance of order_id in left table like ... total orders of user_id 1 with status 5 are 2 but my query return 3 as count (order_id) bcz there are 3 instance of passed orders by user id 1.

Any suggestions or solutions ...i am stuck since long :(

thanks

  • 写回答

1条回答 默认 最新

  • douhan9748 2018-05-16 06:38
    关注

    You need to count the number of distinct occurrences of order_id:

    SELECT h.user_id, 
           COUNT(DISTINCT h.order_id) AS total_orders, 
           SUM(o.quantity) AS quantity 
    FROM table1 h 
    LEFT JOIN table2 o ON o.order_id=h.order_id 
    WHERE h.order_status = 5 
    GROUP BY h.user_id
    

    Also, using IF function inside COUNT like this:

    COUNT(IF(h.order_status = 5,1,0)) AS total_orders
    

    makes no sense since h.order_status is always equal to 5, due to the WHERE clause:

    WHERE h.order_status = 5
    

    Demo here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探