MySQL IF语句,然后在列中计数COUNT个值

时间:2019-03-05 15:18:18

标签: mysql

我是MySQL的新手(使用SQLite)并致力于更复杂的查询

假设我的数据库是

tablename = "stages"

id | results | stage    | parent_id
1  | no      | 'stage1' | 1
2  | no      | 'stage1' | 1
3  | yes     | 'stage1' | 2
4  | no      | 'stage2' | 2

我要执行的查询是添加一个COUNT列,计算results where stage = stage1

的数量

所需的结果将是:

parent_id | stage | stage_no_count | stage_yes_count

我该怎么做?

编辑: 对于所有的答案,谢谢!我只是想了解这种简单查询的逻辑。我可以将其重新应用到更复杂的查询中,但是对于一个简单的示例,我很好奇。

2 个答案:

答案 0 :(得分:2)

使用MySQL,我们可以使用条件聚合。简写如下:

SELECT t.parent_id
     , t.stage
     , SUM(t.results = 'no')    AS stage_no_count
     , SUM(t.results = 'yes')   AS stage_yes_count
  FROM stages t
 GROUP
    BY t.parent_id
     , t.stage

更轻便且符合ANSI SQL标准

SELECT t.parent_id
     , t.stage
     , SUM(CASE t.results WHEN 'no'  THEN 1 ELSE 0 END)  AS stage_no_count
     , SUM(CASE t.results WHEN 'yes' THEN 1 ELSE 0 END)  AS stage_yes_count
  FROM stages t
 GROUP
    BY t.parent_id
     , t.stage

(无论我们返回0还是NULL,对results的NULL值的处理都有细微的差别)

答案 1 :(得分:1)

不知道示例数据和/或预期结果。
我假设您想在parent_id和阶段

上进行PIVOT

拥有COUNT

SELECT
   parent_id
 , stage
 , COUNT(CASE WHEN results = 'no' THEN 1 ELSE NULL END) AS stage_no_count
 , COUNT(CASE WHEN results = 'yes' THEN 1 ELSE NULL END) AS stage_yes_count
FROM 
 stages
GROUP BY
  parent_id
, stage
# if the order is important in the results
ORDER BY 
 parent_id ASC

具有SUM

SELECT
   parent_id
 , stage
 , SUM(CASE WHEN results = 'no' THEN 1 ELSE 0 END) AS stage_no_count
 , SUM(CASE WHEN results = 'yes' THEN 1 ELSE 0 END) AS stage_yes_count
FROM 
 stages
GROUP BY
  parent_id
, stage
# if the order is important in the results
ORDER BY 
 parent_id ASC