类似于此问题:group by not-null values
我正在尝试仅对列groupID
不为空的记录进行分组:
+--+-------+------+-----+-----+----------+
|id|groupId|isMain|name |stars|created |
+--+-------+------+-----+-----+----------+
..1..abcd....1.....john....5...2018-06-01.
..2..NULL....0.....albert..3...2018-05-01.
..3..abcd....0.....clara...1...2018-06-01.
..4..NULL....0.....steph...2...2018-07-01.
通过此查询,我只能将groupId
不为空的那些记录分组:
SELECT *, SUM(stars) as stars
FROM table AS
GROUP BY (case when `groupId` is null then id else `group` end)
ORDER BY created DESC
这给了我结果:
4..NULL....0.....steph...2...2018-07-01
3..NULL....0.....clara...6...2018-06-01
2..NULL....0.....albert..3...2018-05-01
我正在尝试为分组的记录选择isMain
是1
的记录,但是我不知道如何实现。
我尝试过玩HAVING
,但这给了我完全不同的结果。
答案 0 :(得分:2)
您可以使用CASE或IFNULL 但您应该使用适当的聚合函数并按列子句进行分组,例如:
select ifnull(groupID, id), name, sum(stars), max(created) as my_create
from table
group by ifnull(groupID, id), name
order by my_create