您可以将聚集函数SUM()
与IF一起使用,以确定某个值是否出现在GROUP BY组中。
让我们首先创建一个演示表
mysql> create table GroupbygroupDemo -> ( -> UserId int, -> UserName varchar(20) -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into GroupbygroupDemo values(10,'John'); mysql> insert into GroupbygroupDemo values(10,'Carol'); mysql> insert into GroupbygroupDemo values(10,'Carol'); mysql> insert into GroupbygroupDemo values(20,'David'); mysql> insert into GroupbygroupDemo values(30,'John'); mysql> insert into GroupbygroupDemo values(30,'David'); mysql> insert into GroupbygroupDemo values(30,'Mike');
使用select语句显示表中的所有记录。查询如下-
mysql> select *from GroupbygroupDemo;
输出如下
+--------+----------+ | UserId | UserName | +--------+----------+ | 10 | John | | 10 | Carol | | 10 | Carol | | 20 | David | | 30 | John | | 30 | David | | 30 | Mike | +--------+----------+ 7 rows in set (0.00 sec)
这是确定值是否出现在GROUP BY组中的查询
mysql> select UserId, -> if(sum(UserName='David'),'YES','NO') as Correct_Name_David -> from GroupbygroupDemo -> group by UserId;
以下是输出
+--------+--------------------+ | UserId | Correct_Name_David | +--------+--------------------+ | 10 | NO | | 20 | YES | | 30 | YES | +--------+--------------------+ 3 rows in set (0.08 sec)