带计数指令的sql查询结果

时间:2019-05-24 13:22:40

标签: mysql

我无法理解,因为此SQL查询不起作用:

SELECT COUNT Department, 
        IF(Department  = 'toys', COUNT(*), 0) AS nt, 
        IF(Department  = 'health', COUNT(*), 0) AS nh
FROM TABLE;

Department  Value
toys        A
toys        B
toys        C
health      K
health      F
toys        G
toys        R
toys        W
toys        Q

我想将有关玩具记录和健康记录的发生次数统计到两栏中。

department    nt    nh
toys          7     0
health        0     2

为什么?!

谢谢

3 个答案:

答案 0 :(得分:0)

SELECT department,
       SUM(IF(Department  = 'toys',1 , 0)) AS nt, 
       SUM(IF(Department  = 'health', 1, 0)) AS nh
FROM TABLE;

这将使您分为两列。

如果匹配,则只会返回一个总和。

我要推荐的替代查询

SELECT Department, 
       COUNT(*)
FROM TABLE
WHERE Department IN ('toys','health')
GROUP BY Department;

此查询将为您提供部门明智的计数。

答案 1 :(得分:0)

尝试使用条件group by,例如:

select 
Department,
count(case when Department = 'toys' then 1 end) as nt,
count(case when Department = 'health' then 1 end) as nh    
from t
group by Department

答案 2 :(得分:0)

在MySql中,很容易在分组时编写这样的条件聚合表达式,例如:

select
  Department, 
  sum(Department = 'toys') nt,
  sum(Department = 'health') nh
from tablename
group by Department  

请参见demo
结果:

| Department | nt  | nh  |
| ---------- | --- | --- |
| toys       | 7   | 0   |
| health     | 0   | 2   |