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

如何用单条MySQL查询合并同一张表的两类统计结果?

问题描述

现有一张包含name、status、type字段的MySQL表,数据如下:

namestatustype
oneactivepaid
fivenon activefree
tenactivepaid
oneactivepaid
fournon activefree
threeactivepaid
twonon activefree

期望输出同时展示status及其统计数、type及其统计数的表格:

statusstatus counttypetype count
active4free3
non active3paid4

目前可通过两次分组查询分别获取结果:
统计status:

select status, count(status) as `status count`
from your_table 
group by status;

统计type:

select type, count(type) as `type count`
from your_table 
group by type;

请问是否可以通过单条MySQL查询实现上述期望输出,无需执行两次查询?


解决方案

可以通过单条MySQL查询实现目标输出,关键是分别对status和type做分组统计,给每组统计结果添加排序后的行号,再通过行号将两个数据集关联起来。

下面是具体的实现代码(记得把your_table替换成你的实际表名):

MySQL 8.0+版本(支持CTE)

WITH status_stats AS (
    SELECT 
        status, 
        COUNT(status) AS `status count`,
        ROW_NUMBER() OVER (ORDER BY status DESC) AS rn
    FROM your_table
    GROUP BY status
),
type_stats AS (
    SELECT 
        type, 
        COUNT(type) AS `type count`,
        ROW_NUMBER() OVER (ORDER BY type) AS rn
    FROM your_table
    GROUP BY type
)
SELECT 
    s.status, 
    s.`status count`, 
    t.type, 
    t.`type count`
FROM status_stats s
JOIN type_stats t ON s.rn = t.rn;

MySQL 5.x版本(不支持CTE)

如果你的MySQL版本较低,用子查询替代CTE即可:

SELECT 
    s.status, 
    s.`status count`, 
    t.type, 
    t.`type count`
FROM (
    SELECT 
        status, 
        COUNT(status) AS `status count`,
        @rn1 := @rn1 + 1 AS rn
    FROM your_table, (SELECT @rn1 := 0) r
    GROUP BY status
    ORDER BY status DESC
) s
JOIN (
    SELECT 
        type, 
        COUNT(type) AS `type count`,
        @rn2 := @rn2 + 1 AS rn
    FROM your_table, (SELECT @rn2 := 0) r
    GROUP BY type
    ORDER BY type
) t ON s.rn = t.rn;

注意事项

  • 行号的排序规则要和你期望的输出匹配:比如status按DESC排序会让active排在第一行,type按升序排序会让free排在第一行,这样关联后就能得到目标表格结构;
  • 确保分组统计的结果行数一致(这里status和type都是两组,行号能一一对应)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:39:18