Mysql使用if语句聚合数据

时间:2015-01-19 17:08:25

标签: mysql database

我想解决的问题的简化示例:

编辑 - 使用PK

sqlfiddle:http://sqlfiddle.com/#!2/7be5d/1

---

我有两张桌子:

People
--------
| Name |
--------
| Mike |
| Jim  |
| Fred |
--------


HasBanana
------------------------
| Name  | Has_a_banana |
------------------------
| Mike  | N            |
| Mike  | N            |
| Mike  | N            |
| Mike  | N            |
| Mike  | Y            |
| Mike  | N            |
| Jim   | N            |
| Jim   | N            |
| Jim   | Y            |
| Jim   | N            |
| Jim   | N            |
| Fred  | N            |
| Fred  | N            |
| Fred  | N            |
| Fred  | N            |
| Fred  | N            |
| Fred  | N            |
------------------------

一个查询:

select * from People
left join HasBanana on HasBanana.name = People.name;

这会生成一个与上面的HasBanana表完全相同的表。我想要制作的是一个按People.name分组的表格,如果该人被标记为有香蕉,则显示Y.

这样的事情:

HadBanana
------------------------
| Name  | Had_a_banana |
------------------------
| Mike  | Y            |
| Jim   | Y            |
| Fred  | N            |
------------------------

我知道我可以使用以下内容按名称分组

group by people.name;

但是如果has_a_banana曾经是Y,那么在为每个名称说出逻辑时会遇到问题,然后将had_a_banana设置为Y.

4 个答案:

答案 0 :(得分:1)

select 
   p.name
   , case when x.name is null then 'N' else 'Y' end as had_a_banana
from people p
left outer join
(
  select 
     name 
  from bananas
  where has_a_banana = 'Y'
  group by name
) x
on x.name = p.name
group by p.name, x.name

我已经使用你的SQLFiddle链接检查了这个,虽然你的小提琴数据与你的问题不符,所以我得到:

Fred  N
Jim   Y
Mike  N

(这似乎与你的小提琴数据相符)。

答案 1 :(得分:1)

替代方案(丑陋的解决方案):

select people.name, max(has_a_banana) from people
left join bananas on bananas.name = people.name
group by people.name;

答案 2 :(得分:0)

select people.id, people.name, case a.has_a_banana when 'Y' then 'Y' else 'N' end as has_a_banana from people
left join 
(select people.id, people.name, bananas.has_a_banana from people
left join bananas on bananas.name = people.name
where has_a_banana = 'Y'
group by people.name) as a 
on a.name = people.name

select people.id, people.name, case a.has_a_banana when 'Y' then 'Y' else 'N' end as has_a_banana from people left join (select people.id, people.name, bananas.has_a_banana from people left join bananas on bananas.name = people.name where has_a_banana = 'Y' group by people.name) as a on a.name = people.name

应该让你得到你想要的。

答案 3 :(得分:0)

E.g:

SELECT DISTINCT x.name
              , COALESCE(y.has_a_banana,x.has_a_banana) has_a_banana
           FROM bananas x
           LEFT 
           JOIN bananas y
             ON y.name = x.name
            AND y.has_a_banana = 'y'

http://sqlfiddle.com/#!2/7be5d/25