使用GROUP BY IN MYSQL计算特定行总数的状态列上的id计数

时间:2015-01-08 06:29:07

标签: mysql sql group-by aggregate-functions

我有以下mysql表

id  status
------------
1   available
2   hold
3   available
4   so-hold
5   so-hold
6   hold
7   hold
8   available

当我在GROUP BY coloumn上使用STATUS时,我得到了以下内容:

count(id)   status
---------------------
3           available
3           hold
2           so-hold

status coloumn ' hold' ' so-hold' 属于同一类别,所以我需要按以下方式计算:

count(id)   status
---------------------
3           available
5           hold

以下是我目前使用的MySQL查询:

SELECT count(id), status FROM `inventory_master` GROUP BY status

6 个答案:

答案 0 :(得分:1)

您可以使用CASE声明

select 
count(id),
case when status = 'so-hold'
     then 'hold'
     else status
end as status_col
from inventory_master
group by status_col

DEMO

答案 1 :(得分:0)

尝试更换"所以 - "使用空字符串然后尝试查询如下:

SELECT newStatus, COUNT(*)
FROM
(SELECT REPLACE(status, 'so-', '') as newStatus
 FROM MYTABLE) AS tab
 GROUP BY newStatus

答案 2 :(得分:0)

您可以尝试这样的事情:

SELECT COUNT(*), status FROM table WHERE status NOT IN('hold', 'so-hold') GROUP BY status
UNION
SELECT COUNT(*), 'hold' FROM table WHERE status IN('hold', 'so-hold')

首先是COUNT个普通群组,然后是UNION COUNThold + so-hold

SQLFiddle

答案 3 :(得分:0)

在这种情况下你可以使用案例:

select status, count(*) from `inventory_master`  group by case status when 'so-hold' then 'hold' else status end;

答案 4 :(得分:0)

两个步骤。首先(Sub-Select使用CASE替换'so-hold'到'hold')。第二步GROUP BY。

SELECT g1.status, COUNT(*)
  FROM ( SELECT CASE status
                 WHEN 'so-hold' THEN 'hold'
                 ELSE status
                END AS status,
                id
           FROM test_tw
        ) g1
GROUP BY g1.status
ORDER BY g1.status;

(用ORACLE测试)

答案 5 :(得分:0)

试试这个

Select Case When status='So-Hold' Then 'Hold' Else status End,COUNT(*) 
From TableName
Group by Case When status='So-Hold' Then 'Hold' Else status End