针对不同条件的不同选择语句

时间:2014-08-18 06:52:27

标签: mysql sql conditional-statements

这是我当前的mysql查询。

sqlfiddle中的当前表查询 http://sqlfiddle.com/#!2/6e0420

如果我select * from table,我会得到以下

RN  PC  PC1 GRP E_ID
111 A1  A1  175 100
112 A1  A2  100 90
113 B1  B3  101 90
114 B1  B1  100 90
115 B1  B5  100 90
116 C1  C1  100 90

但我正在尝试获得此输出

RN  PC  PC1 GRP E_ID
111 A1  A1  175 100
112 A1  A2  
113 B1  B3  
114 B1  B1  100 90
115 B1  B5  
116 C1  C1  100 90

所以条件是如果pc = pc1那么应该显示grp和e_id, 否则如果pc!= pc1则grp和e_id应为空

 Current query 
        select *
        from table1 
        where rn in(select rn from table1 group by rn having count(*)=1)
        AND (pc = pc1)


 Solution
       select rn, pc, pc1, 
       case when pc = pc1 then grp else null end as grp,
       case when pc = pc1 then e_id else null end as e_id
       from table1
       where rn in(select rn from table1 group by rn having count(*)=1)

QN2:上面的解决方案我添加了count = 1,因为如果计数是>我有另一个sql查询1.我如何组合查询,基本上按count = 1和count> 1进行拆分 下面是sql查询

select *
from table1 
where rn in(select rn from table1 group by rn having count(*)>1)
AND (pc = pc1)
AND grp in (select max(grp) from table1)
AND e_id in( select min(e_id) from table1)

count> 1的条件不会影响count = 1的结果。

我已经找到了解决方案,即将它们联合起来。谢谢你的第一部分。

1 个答案:

答案 0 :(得分:3)

您可以使用case when,并在pc <> pc1

时显示空(或其他内容)
select rn, pc, pc1, 
       case when pc = pc1 then grp else null end as grp,
       case when pc = pc1 then e_id else null end as e_id
from table1

可以简化(替换空值)

select rn, pc, pc1, 
       case when pc = pc1 then grp end as grp,
       case when pc = pc1 then e_id  end as e_id
from table1