You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL单查询内连接(非GROUP BY)实现双条件count(id)统计

Solution Query

Got it, let's work through this. Here's the MySQL query that checks all your boxes — uses INNER JOIN, skips the GROUP BY clause, and counts orders by each status for customers who have placed orders:

SELECT DISTINCT
    c.customer_id,
    c.customer_name,
    (SELECT COUNT(order_id) FROM orders o2 WHERE o2.customer_id = c.customer_id AND o2.order_status = 'success') AS success_count,
    (SELECT COUNT(order_id) FROM orders o2 WHERE o2.customer_id = c.customer_id AND o2.order_status = 'rejected') AS rejected_count,
    (SELECT COUNT(order_id) FROM orders o2 WHERE o2.customer_id = c.customer_id AND o2.order_status = 'pending') AS pending_count
FROM customer c
INNER JOIN orders o ON c.customer_id = o.customer_id;

Breakdown of how this works:

  • INNER JOIN: We join customer with orders to only include customers who have at least one order (so customer04 and customer05 get excluded, which aligns with inner join behavior).
  • DISTINCT: Since the inner join would return one row per order, we use DISTINCT to collapse duplicate customer rows into a single entry per customer.
  • Correlated Subqueries: Each subquery calculates the count of orders for a specific status tied to the current customer in the main query. This lets us get per-customer status counts without needing GROUP BY.

When you run this, you'll get a result set that matches the stats you listed:

  • customer01: 2 success, 1 rejected, 1 pending
  • customer02: 2 success, 0 rejected, 1 pending
  • customer03: 0 success, 0 rejected, 1 pending

内容的提问来源于stack exchange,提问作者Zinc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:28:45