例如,当列1为空时,则为NULL ELSE column2 END

时间:2015-06-25 07:34:45

标签: mysql sql case

我只是在upvote表中提取comment的总数,但希望最后一行在NULL列中打印content

以下是我尝试运行的简单查询:

SELECT
    id
    , content -- THIS IS JUST TO COMPARE, WE DON'T NEED THIS
    , (CASE WHEN id IS NULL THEN NULL ELSE content END) as editedContent -- WE NEED THIS(WITH NULL VALUE IN THE END)
    , SUM(upvote)
FROM `test`.`comment`
GROUP BY id WITH ROLLUP

输出:

+------+-------------+---------------+-------------+
| id   | content     | editedContent | SUM(upvote) |
+------+-------------+---------------+-------------+
| 26   | Content13-2 | Content14-1   |           2 |
| 27   | Content14-1 | Content14-2   |           2 |
| 28   | Content14-2 | Content15-1   |           2 |
| 29   | Content15-1 | Content15-2   |           3 |
| 30   | Content15-2 | Content15-2   |           2 |
| NULL | Content15-2 | Content15-2   |          55 |
+------+-------------+---------------+-------------+
6 rows in set (0.00 sec)

预期产出:

+------+-------------+---------------+-------------+
| id   | content     | editedContent | SUM(upvote) |
+------+-------------+---------------+-------------+
| 26   | Content13-2 | Content13-2   |           2 |
| 27   | Content14-1 | Content14-1   |           2 |
| 28   | Content14-2 | Content14-2   |           2 |
| 29   | Content15-1 | Content15-1   |           3 |
| 30   | Content15-2 | Content15-2   |           2 |
| NULL | Content15-2 | NULL          |          55 |
+------+-------------+---------------+-------------+
6 rows in set (0.00 sec)

2 个答案:

答案 0 :(得分:3)

尝试以下,

SELECT
    id
    , content -- THIS IS JUST TO COMPARE, WE DON'T NEED THIS
    , (CASE WHEN id IS NULL THEN NULL ELSE content END) as editedContent -- WE NEED THIS(WITH NULL VALUE IN THE END)
    , SUM(upvote)
FROM `test`.`comment`
GROUP BY id 

Union all

select 
    'null',
    'null',
    'null',
    SUM(upvote)
from comment

答案 1 :(得分:0)

尝试此查询

SELECT
    id
    , content -- THIS IS JUST TO COMPARE, WE DON'T NEED THIS
    , (CASE WHEN id IS NULL THEN id ELSE content END) as editedContent -- WE NEED THIS(WITH NULL VALUE IN THE END)
    , SUM(upvote)
FROM `test`.`comment`
GROUP BY id WITH ROLLUP