MySQL IF语句然后在列中计算值
我不熟悉MySQL(使用SQLite),正在处理更复杂的查询 假设我的数据库是MySQL IF语句然后在列中计算值,mysql,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列,计算结果的数量,其中stage=stag
tablename = "stages"
id | results | stage | parent_id
1 | no | 'stage1' | 1
2 | no | 'stage1' | 1
3 | yes | 'stage1' | 2
4 | no | 'stage2' | 2
我试图做的查询是添加一个COUNT
列,计算结果的数量,其中stage=stage1
预期的结果将是:
parent_id | stage | stage_no_count | stage_yes_count
我该怎么做呢
编辑:
对于所有的答案,谢谢!我只是想理解这样一个简单查询的逻辑。我可以将其重新应用到更复杂的查询中,但对于一个简单的示例,我很好奇该如何做 对于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,处理NULL值都有细微差别)不知道示例数据和/或预期结果我想你应该关注家长id和舞台 计数
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
总计
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
哪个MySQL版本<代码>选择版本()?不是按阶段1/2nm,按组解决这个什么<代码>计数(0)?没有关系。。似乎为OP工作。谁需要ecact号码?;-)实际上,
COUNT(0)
转换为1
我在想什么?谢谢@PaulSpiegel我需要咖啡..等等,这不算整个舞台吗是/否?ie-如果第1阶段是否定的,第2阶段是否定的,我不想只回答第1阶段的“否”,如果我的回答没有帮助,请参见你问题下的我的评论@摩根纳先生,你的回答很有效!直到我玩了它,我才明白它是怎么工作的。它现在是有意义的,并且按照预期工作