在单个查询中从两个不同的条件中获取不同的值

时间:2014-02-25 06:18:59

标签: sql postgresql case

我需要有如下结果

section_one | section_two
56788              678

这是我写的分别具有上述结果的查询

Select count(*) as section_one from tableNew
WHERE columnone LIKE %hjk%

并且

Select count(*) as section_two from tableNew
WHERE columnone NOT LIKE %hjk%;

如何在一个查询中组合这两个并得到上面的结果?

我在下面试了一下,但似乎没有正常工作

select *,
CASE
WHEN columnone LIKE %hjk% THEN count(1) as section_one
ELSE count(1) as section_two
END
from tableNew
Group by tableid;

还有其他方法可以在一个查询中同时使用这两个条件吗? 对此的任何帮助都会很棒!

P.S:还有其他方法来检查boolean条件,而不是columnone LIKE %hjk%定位columnone IS NOT NULL

1 个答案:

答案 0 :(得分:1)

使用SUM

尝试此操作
select 
SUM(columnone LIKE %hjk%)  as section_one,
SUM(columnone NOT LIKE %hjk%)  as section_two
from tableNew
Group by tableid;

或者您可以使用CASE

select 
SUM(CASE WHEN columnone LIKE %hjk% THEN 1 ELSE 0 END)  as section_one,
SUM(CASE WHEN columnone NOT LIKE %hjk% THEN 1 ELSE 0 END)  as section_two
from tableNew
Group by tableid;