0. 主要用途
- 数据转换: 在查询中根据不同条件返回不同的结果。
- 数据清洗: 处理数据中的异常值或分类数据。
- 业务逻辑: 在 SQL 查询中嵌入业务规则
本文主要包含各语言的条件筛选: /filter /case-when/ if/ decode
1. PostgreSQL
- 当发现可以进行筛选时,语句如下:
SELECT
count(*) filter (where PERIOD = '01') AS business_daily, -- 日累计 业务办理
count(*) filter (where PERIOD = '02') AS business_per_month -- 月累计 业务办理
FROM
`k_id_idx` as ki
WHERE idx_code = 'GD010'
2. MySQL
- 上面的
count-filter
语句并不能使用在 mysql 中使用,但是 count 函数和 if 函数结合可以达到同样的效果,语句如下:
COUNT() 函数
统计数据表中的行的总数,忽略空值
IF(expr, v1, v2) 函数
if(expr, v1, v2) 表达式expr为true (expr<>0 and expr <> NULL) 返回v1,否则v2
IFNULL(expr1, expr2)
-- MySQL / SQLite
SELECT IFNULL(column1, ‘Default’) FROM table;
SELECT
count(if(PERIOD = '01', pid, null)),
count(DISTINCT if(PERIOD = '02', pid, null)) -- 如果返回字段结果不唯一的话,可加上 DISTINCT 去掉重复字段再统计,这里用 1 来标记的话,不可用 DISTINCT;
FROM `k_id_idx`
WHERE idx_code = '010'
根据原理,可使用 sum 函数加上 if 函数,用 1 来标记累加,效果相同;(用 1 标记,count/sum 不可用 DISTINCT 去重)
SELECT
sum(if(PERIOD = '01', 1, 0)),
sum(if(PERIOD = '02', 1, 0)) -- 如果存在累加 1 ,没有累加 0;
FROM `k_id_idx`
WHERE idx_code = '010'
3. Oracle
- CASE WHEN 语句:
select
sum(case u.sex when 1 then 1 else 0 end) as '男性',
sum(case u.sex when 2 then 1 else 0 end) as '女性',
sum(case when u.sex <>1 and u.sex<>2 then 1 else 0 end) as '性别为空'
from users u;
-- 或者
select
sum(case u.sex when 1 then 1 end) as '男性',
sum(case u.sex when 2 then 1 end) as '女性',
sum(case when u.sex <>1 and u.sex<>2 then 1 end) as '性别为空'
from users u;
# 常见 case when 字典替换功能
select u.id,u.name,
(case u.sex
when 1 then '男'
when 2 then '女'
else '空的'
end
) as '性别'
from users u;
- NVL 空值判断 Oracle 专有
NVL 用于处理 NULL 值。如果第一个参数为 NULL,则返回第二个参数;否则返回第一个参数。
-- 使用 NVL
TO_CHAR(NVL(u.could_be_null, u.candidate)) "空值判断"
- DECODE(expr, search1, result1, search2, result2, …, default_result) Oracle 专有
-- 使用 DECODE
TO_CHAR(DECODE(u.could_be_null, NULL, u.candidate, u.default_column)) AS "空值判断"
4. 字符串拼接
- MySQL / MariaDB: 使用 CONCAT 函数。
- PostgreSQL / SQLite / Oracle: 使用 || 运算符。
- SQL Server: 使用 + 运算符。
# mysql
SELECT CONCAT(column1, ' ', column2) AS full_name FROM users;
# postgres sqlite oracle
SELECT column1 || ' ' || column2 AS full_name FROM users;
# sqlserver
SELECT column1 + ' ' + column2 AS full_name FROM users;
- demo
# oracle
SELECT 'UPDATE users SET name = ''' || 'jerry' || ''', age = ' || 3 || ' WHERE id = ''' || '001' || ''';' AS UPDATE_STATEMENT
FROM DUAL;
(END)