0

我正在使用 MySQL 数据库,并且我有一个很大的 mysql_query,除了这一行之外,它工作得很好。

SELECT game_id, 
COALESCE(
SUM(CASE WHEN game_score = 1 THEN 1 ELSE 0 END) 
- 
SUM(CASE WHEN game_score = 0 THEN 1 ELSE 0 END), 0) AS score 
FROM .... 
WHERE .... 
GROUP BY ....

这一行几乎返回了我想要的所有数字,但它们与我不使用该COALESCE函数时的数字相同。当有game_score` 字段
时,我希望此语句返回 0 。 我的代码哪里出错了? game_id that has an empty

4

5 回答 5

2

你也可以像这样使用解码功能---

SELECT game_id, 
SUM(DECODE(game_score, null, 0, 0, -1, 1, 0)) AS score 
FROM .... 
WHERE .... 
GROUP BY ....

我已经检查了此查询是否有效,
希望它对您有所帮助....

于 2012-05-24T04:56:18.830 回答
1

添加

when game_score is null then ...

编辑

SELECT game_id, case when game_score is null then 0 else
                SUM(CASE WHEN game_score = 1 THEN 1 ELSE 0 END) 
                -
                SUM(CASE WHEN game_score = 0 THEN 1 ELSE 0 END) end AS score 
FROM games
group by ...

请参阅此SQLFiddle 示例

于 2012-05-23T20:13:39.187 回答
0

Use the COALESCE function around your field name in your statements instead of surrounding the SUM function:

SUM(CASE COALESCE(game_score,0) WHEN 1 THEN 1 ELSE 0 END) - SUM(CASE COALESCE(game_score,0) WHEN 0 THEN 1 ELSE 0 END) 
于 2012-05-23T20:24:25.087 回答
0

The problem is that game_id can have an empty game_score field in one row and a valid one in another. Your code picks up the valid one and returns non-null.

Fix this problem by looking for this case explicitly, as the first argument to coalesce: SELECT game_id, (CASE WHEN count(*) <> count(game_score) then NULL ELSE COALESCE(SUM(CASE WHEN game_score = 1 THEN 1 ELSE 0 END), . . .

I'm not sure what the coalesce is trying to do. It seems to be adding one for a bunch of different game_scores. Can you use one of the following instead:

COUNT(game_score) ?

SUM(case when game_score between 1 and xx then 1 else 0 end) ?
于 2012-05-23T20:24:55.867 回答
0

使用is null喜欢

CASE WHEN game_score = 1 THEN 1 
when game_score is null THEN 0
ELSE 0 END
于 2012-05-23T20:16:04.163 回答