mysql-count(id)在1个查询中使用2个不同的子句(使用内部连接,而不是group-by)

kkbh8khc  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(314)

我有两个表(客户和订单)包含:

// Customer Table
customer_id     customer_name     customer_address
     1            customer01          address01
     2            customer02          address02
     3            customer03          address03
     4            customer04          address04
     5            customer05          address05

// Orders Table
order_id    customer_id    order_status
    1             1           rejected
    2             1           success
    3             2           success
    4             1           success
    5             1           pending
    6             2           success
    7             2           pending
    8             3           pending

所以,在我的订单表中:
客户01 2 success , 1 rejected 以及 1 pending 客户02 2 success 以及 1 pending customer03只有 1 pending 期望:我需要的结果

customer_id   Customer_name (success)   order_status
     1           customer01 (2)           pending
     2           customer02 (2)           pending
     3           customer03 (0)           pending

我的查询:在sqlfiddle上使用示例数据

SELECT o.order_id, c.customer_id, CONCAT(c.customer_name, " (", (SELECT COUNT(order_id) FROM orders WHERE order_status = 'success'),")") as "Customer Name (success order)", o.order_status
FROM customer c
INNER JOIN orders o ON c.customer_id = o.customer_id
WHERE o.order_status = 'pending'
ORDER BY c.customer_id ASC;

结果

customer_id   Customer_name (success)   order_status
     1           customer01 (4)           pending
     2           customer02 (4)           pending
     3           customer03 (4)           pending

编辑:删除sql fiddle。

7fhtutme

7fhtutme1#

子查询和主查询之间缺少获取相关计数的链接

(SELECT COUNT(order_id) FROM orders WHERE order_status = 'success'
 and customer_id = c.customer_id   --- you need to link the sub and the mainquery
)
jxct1oxe

jxct1oxe2#

目前尚不清楚这一状况是如何计算的。而且,sql fiddle上的数据与问题中的数据不同。
但我想这正是你想要的:

SELECT c.c_id, 
       CONCAT(c.c_name, " (", SUM(o.o_status = 'success'), ")") as "Customer Name (Success Order Count)",
       min(o.o_status)
FROM customer c INNER JOIN
     orders o
     ON c.c_id = o.c_id 
GROUP BY c.c_id ASC, c.c_name;

sql小提琴在这里。

相关问题