赞
踩
coalesce()返回参数中的第一个非空表达式
select coalesce(null,2,3) return 2;
select coalesce(1,2,3) return 1;
查询表中各年月销量与上月销量的差值,按年月顺序排序,结果输出年、月、销量、与上月销量的差值
SELECT
a.TYEAR,
a.TMONTH,
a.TAMOUNT,
a.TAMOUNT - COALESCE(b.TAMOUNT, 0) AS DELTA
FROM
test_mount
a
LEFT JOINtest_mount
b ON
IF(
a.TMONTH = 1,
a.TYEAR -1,
a.TYEAR
) = b.TYEAR AND IF(a.TMONTH = 1, 12, a.TMONTH - 1) = b.TMONTH
查询表中各年月销量与上一个临近月销量的差值,按年、月顺序排序,结果输出年、月、销量、与上一个临近月销量的差值。
SELECT
TYEAR,
TMONTH,
TAMOUNT,
TAMOUNT - TAMOUNT_PRE AS DELTA
FROM
(
SELECT
TYEAR,
TMONTH,
TAMOUNT,
lag(TAMOUNT, 1, 0) over(
ORDER BY
TYEAR,
TMONTH
) AS TAMOUNT_PRE
FROM
test_mount
) a
lag() over() 从同一结果集中的当前行访问上一行的数据(php8的新函数,老版本不能用)
concat 进行修改数据:
update TABLE_I i
LEFT JOIN TABLE_M m ON i.submitter_uid = m.uid
set i.email = concat(m.qq,‘@qq.com’)
WHERE i.email = ‘’
and i.placeholder_status = 0
and i.submitter_uid not in (387992,1,2)
and i.title != ‘****’;
concat () 进行数据查询
SELECT concat(username,‘123123’) as uname,username FROM
members
WHERE uid=121331;
selcet * from table where type = 1 and status in (select status from status_table) and name is not null;
SELECT * FROM order WHERE EXISTS ( SELECT 1 FROM invoice_order WHERE invoice_order.oid = order.id );
使用 UNION 把上面两种结果集并到一起,查询出来的数据没有重复数据。
select * from teacher where age >20 union all select * from teacher where age>25;
注意:查询出来的结果会有重复的数据
select distinct area from table;
select name,if(age>17,‘成年’,‘未成年’) as age_group,id_number from student;
select name,age,id_number,ifnull(email,‘default@qq.com’) as full_email from teacher;
IFNULL(email,‘default@qq.com’) 表示若 email 字段为 NULL ,则展示为 default @qq.com
where是从查询满足条件的数据,用于查询数据之前;
WHERE子句作用于基表或视图,从中选择满足条件的元组
having用于在查出的数据中挑选满足条件的数据,在数据查出来之后处理。
HAVING短语作用于组,从中选择满足条件的组
select class,sum(CASE WHEN sex=1 THEN population else 0 end) as cnt_m,
sum(CASE WHEN sex=2 THEN population ELSE 0 END) AS cnt_f
from school_test group by class;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。