【Leecode-专项突破-SQL入门】day3

这次的专项训练集中在字符串处理函数/正则表达式上,相对个人而言,如果了解某些字符串处理函数,问题解决起来会很直接方便,否则处理起来会异常麻烦。SQL正则表达式不算困难,如果你有java正则编写经验的话。
总共 3 道题:3 简单

1667.修复表中的名字

Table Users

user_idname
1aLice
2boB

编写一个 SQL 查询来修复名字,使得只有第一个字符是大写的,其余都是小写的,返回按 user_id 排序的结果表。

select user_id,
  concat(upper(left(name,1)),substr(lower(name),2)) as 'name'
from Users
order by user_id;

在对表中每一行数据查询时,直接对字段截取,转大小写,拼凑,得到目标表

1484.按日期分组销售产品

Table Activities

+------------+-------------+
| sell_date  | product     |
+------------+-------------+
| 2020-05-30 | Headphone   |
| 2020-06-01 | Pencil      |
| 2020-06-02 | Mask        |
| 2020-05-30 | Basketball  |
| 2020-06-01 | Bible       |
| 2020-06-02 | Mask        |
| 2020-05-30 | T-Shirt     |
+------------+-------------+

编写一个 SQL 查询来查找每个日期、销售的不同产品的数量及其名称。每个日期的销售产品名称应按词典序排列。返回按 sell_date 排序的结果表。

输出:
+------------+----------+------------------------------+
| sell_date  | num_sold | products                     |
+------------+----------+------------------------------+
| 2020-05-30 | 3        | Basketball,Headphone,T-shirt |
| 2020-06-01 | 2        | Bible,Pencil                 |
| 2020-06-02 | 1        | Mask                         |
+------------+----------+------------------------------+

按照要求应显示成如上形式。

select sell_date
  ,count(distinct product) as 'num_sold'
  ,group_concat(distinct product order by product separator ',') as products
from Activities
group by sell_date
order by sell_date

这里我们用到了 group_concat() 函数,它将由 group by sell_date 后产生的 product 通过指定的 separator ‘,’ 链接字段 product 值,根据题意,我们需要对产品类去重,即使用 distinct product。

1527.患某种疾病的患者

Table Patients

+------------+--------------+--------------+
| patient_id | patient_name | conditions   |
+------------+--------------+--------------+
| 1          | Daniel       | YFEV COUGH   |
| 2          | Alice        |              |
| 3          | Bob          | DIAB100 MYOP |
| 4          | George       | ACNE DIAB100 |
| 5          | Alain        | DIAB201      |
+------------+--------------+--------------+
'conditions' (疾病)包含 0 个或以上的疾病代码,以空格分隔

写一条 SQL 语句,查询患有 I 类糖尿病的患者 ID (patient_id)、患者姓名(patient_name)以及其患有的所有疾病代码(conditions)。I 类糖尿病的代码总是包含前缀 DIAB1。按任意顺序返回结果表。

select patient_id,patient_name,conditions
  from Patients where conditions like "DIAB1%" or conditions like "% DIAB1%"

通过正则表达式,匹配符合条件的字段值。需要注意的是 DIAB1 字符可能出现在字段值中间,只通过语句 where conditions like “%DIAB1%” 条件匹配,可能会筛选出错误的值。

–day3学习分享到这里就结束啦
–周末啦,放松一下吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值