SQL 查询
CASE
CASE表达式可以在SQL中实现if-then-else型的逻辑。 语法:
--简单case表达式,使用表达式确定返回值
CASE search_expr
WHEN exp1 THEN result1
WHEN exp2 THEN result2
...
WHEN expN THEN resultN
ELSE default_result
END
--搜索case表达式,使用条件确定返回值
CASE
WHEN cond1 THEN result1
WHEN cond2 THEN result2
WHEN condN THEN resultN
ELSE default_result
END
eg:
select num,state,
case state
when 'TERMINATED' then '终止'
when 'EFFECTIVE' then '有效'
when 'INVALID' then '作废'
else '其他'
end
from cms_contract where num like '%OT%'
select num,state,
CASE
when state='TERMINATED' then '终止'
when state='EFFECTIVE' then '有效'
when state='INVALID' then '作废'
else '其他'
END
from cms_contract where num like '%OT%'
CONNECT BY 和 START WITH
connect by 和 start with 子句可以执行层次化查询。
语法:
SELECT [LEVEL],column,expression,... FROM table
[WHERE where_clause]
[[START WITH start_condition][CONNECT BY PRIOD priod_condition]]
LEVEL
为伪列,代表树的第几层。对根节点为1,子节点依次+1。
start_condition
定义了层次化查询的起点,依次向父节点查找。
prior_condition
定义了父行和子行之间的关系,父->子,父在前。
eg:
select level,name, email, jobname
from cms_sys_users
start with id = 44128
connect by prior super_user_id = id
GROUP BY 和 HAVING
GROUP BY
能够将行分组为具有相同列的多个部分。HAVING
可以用于过滤。
语法:
SELECT ... FROM ...
WHERE ...
GROUP BY ... HAVING ...
ORDER BY ...
eg:
select apply_user_id,count(num) from cms_contract
group by apply_user_id
having apply_user_id in (807920,37656)
UNION
UNION ALL 返回各个查询检索出的所有行,包括重复行
UNION 返回各个查询检索出的所有行,不包括重复行
INTERSECT 返回两个查询检索出的共有行
MINUS 返回(第一个查询 - 第二个查询)检出行
需要说明 eg:
select id,name from table1
minus
select id,name from table2