这是我参加[第四届青训营]笔记创作活动的第12天。
分组之后再筛选 `
-- 分组之后再筛选 -- group by client_id
-- having total_sales > 500
后面只能选择已经被select的列
-- 用于汇总数据 /* group by state,city with rollup*/`
**-- 编写复杂查询 **
-- 第七章
数据操作以及字符串操作
数值函数:
-- 数值函数
-- round(5.73,1) 四舍五入
-- truncate(5.7345,2)截断
-- ceiling(5.2) 大于其的最小整数
-- abs(-5.2) 取绝对值
-- rand()生成0-1之间的浮点数
字符串函数:
-- 字符串函数
-- lenth('sky')获得长度
-- upper大小写lower
-- 删除空格 ltrim rtrim trim
-- 获得字符 left('jfjjjjjdws',4)
-- substring('djvwelkkf',3,2) 得到vw
-- locate('n','kinder') 得到3
-- replace('kindergarten','garten','garden')
-- concat('aa','vv') 得到aavv
日期函数:
-- 日期函数
-- select now(),curdate(),curtime(),year(now()),dayname(now()),extract(year from now())
-- 格式化时间,日期函数
/*select date_format(now(),'%m %d %Y')*/
-- 计算日期和时间
-- 增加一年时间
-- select date_add(now(), interval 1 year)
/*select datediff('2019-01-05 09:00','2020-01-06 09:00')
select time_to_sec('09:00')获得秒数,从午夜开始*/
其他有用的函数ifnull:
-- 其他有用的函数
-- ifnull coalesce
/*select
order_id,
ifnull(shipper_id,'Not assigned') as shipper
from orders*/
select
order_id,
coalesce(shipper_id, comments,'Not assigned') as shipper
from orders
if 函数:
-- if 函数
/*select
order_id,
order_date,
if(
year(order_date)= 2019,
'ac',
'ra') as hu
from orders*/
练习题,小的,其实比较综合啦
select
product_id,
name,
count(*) as orders,
-- 先把有几列先数出来
if(count(*) > 1, 'many times','once') as frequency
from products
join order_items
using(product_id)
group by product_id,name -- 这个就可以分类啦,根据product_id
得到对应的结果:
| 1 | Foam Dinner Plate | 3 | many times | |
|---|---|---|---|---|
| 2 | Pork - Bacon,back Peameal | 2 | many times | |
| 3 | Lettuce - Romaine, Heart | 4 | many times | |
| 4 | Brocolinni - Gaylan, Chinese | 2 | many times | |
| 5 | Sauce - Ranch Dressing | 2 | many times | |
| 6 | Petit Baguette | 2 | many times | |
| 8 | Island Oasis - Raspberry | 1 | once | |
| 9 | Longan | 1 | once | |
| 10 | Broom - Push | 1 | once | |
| --- | --- | |||
最后一个啦,case: 就是一个,怎么说呢,比较复杂的if函数:
-- case函数
select
order_id,
case
when year(order_date) =2019 then 'qq'
when year(order_date) =2018 then 'qqq'
when year(order_date) =2017 then 'qqqq'
else 'future'
end as category
from orders