给出表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行。
答案 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;