如何确定值是否出现在GROUP BY组中

时间:2012-05-11 05:32:58

标签: mysql

给出表foo

Num   Letter
------------
1     A
1     B
1     B
2     C
3     A
3     C
3     D

如果我SELECT * GROUP BY Num我当然得到这样的话:

Num   Letter
------------
1     A
2     C
3     A

我想要改进的是:

Num   Has_No_Letter_C
---------------------
1     Yes
2     No
3     No

可能有一个简单的SELECT IF ()加上ORDER BY,但我现在看不到它......

在我的实际示例中,结果表是LEFT JOIN到另一个表,我希望能够拒绝No条目,但如果我的其他人保留NULL s表bar有一个Num = 4行。

2 个答案:

答案 0 :(得分:17)

SUM(condition)

中使用IF
SELECT   Num,
         IF(SUM(Letter = 'C'), 'Yes', 'No') AS Has_Letter_C
FROM     my_table
GROUP BY Num

您的JOIN随后变为:

SELECT   another_table.Num
FROM     another_table LEFT JOIN my_table ON another_table.Num = my_table.Num
GROUP BY another_table.Num
HAVING   my_table.Num IS NULL OR SUM(my_table.Letter = 'C') > 0

答案 1 :(得分:1)

如果您LEFT JOIN表格本身,您可以轻松确定是否有相应的值。

如果你考虑值“C”,这就完成了工作:

SELECT    t1.num, 
          IF(ISNULL(t2.num),"Yes","No") AS "Has_No_Letter_C"
FROM      yourtable AS t1
LEFT JOIN yourtable AS t2 ON t1.num=t2.num AND t2.`letter` = "C"
GROUP BY  num;