Leetcode SQL (#1517, #1527, #1532, #1543)

1517. Find Users with Valid E-Mails

Question:

https://leetcode.com/problems/find-users-with-valid-e-mails/

Solution:

select 
user_id,
name,
mail
from Users
where 
mail regexp "^[a-zA-Z]+[a-zA-Z0-9_\\./\\-]{0,}@leetcode\\.com$"
order by user_id

1527. Patients with a Condition

Question:

https://leetcode.com/problems/patients-with-a-condition/

Solution:

select 
patient_id, 
patient_name, 
conditions
from Patients
where conditions like "%DIAB1%"
and conditions not like "SADIAB1%"


1532. The Most Recent Three Orders

Question:

https://leetcode.com/problems/the-most-recent-three-orders/

Solution:

select 
o.name as customer_name, 
o.customer_id, 
o.order_id, 
o.order_date
from(
    select 
    o.customer_id, 
    c.name, 
    order_date, 
    order_id,
    dense_rank() over(partition by customer_id order by order_date desc) as r,
    count(order_id) over(partition by customer_id) as orders
    from Orders o
        left join Customers c 
            on o.customer_id= c.customer_id
) o
where (
o.r <= 3 
or o.orders < 3
    )
order by 1, 2, 4 desc

1543. Fix Product Name Format

Question:

https://leetcode.com/problems/fix-product-name-format/

Solution:

select 
lower(trim(product_name)) as product_name, 
date_format(sale_date,'%Y-%m') as sale_date, 
count(distinct sale_id) as total
from sales
group by 1,2
order by 1,2