9

给定表格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,但我现在看不到它......

在我的真实示例中,结果表被编辑到另一个表中,如果我的另一个表有= 4 行LEFT JOIN,我希望能够拒绝No条目但保留NULLs 。barNum

4

2 回答 2

19

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
于 2012-05-11T05:47:03.690 回答
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;
于 2012-05-11T05:46:30.157 回答