Skip to content

yangshiteng/SQL-Practice

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 

Repository files navigation

1789. Primary Department for Each Employee

image

image

Solution1: (Union)

(select employee_id, department_id
from employee
where primary_flag = "Y")
union
(select employee_id, department_id
from employee
group by employee_id
having count(employee_id) = 1)

Solution2: (Window Function)

select t.employee_id, t.department_id
from (select *, count(employee_id) over(partition by employee_id) as C 
from employee) t
where t.C = 1 or t.primary_flag = "Y"

Solution3: (coalesce) (case when then else end) (if)

image

select employee_id, coalesce(max(case when primary_flag = "Y" then department_id else null end), department_id) department_id
from employee
group by employee_id

select employee_id,coalesce(max(if(primary_flag = "Y", department_id, null)), department_id) department_id
from employee
group by employee_id

1795. Rearrange Products Table

image

image

Solution 1: (UNION)

(select product_id, "store1" as store, store1 as price
from Products
where store1 is not null)
union
(select product_id, "store2" as store, store2 as price
from Products
where store2 is not null)
union
(select product_id, "store3" as store, store3 as price
from Products
where store3 is not null)

Solution 2: (UNPIVOT) (MS SQL)

select product_id,store,price 
from Products
UNPIVOT
(
price
for store in (store1,store2,store3)
) as T

1421. NPV Queries

image

image

image

Solution 1: (left join) (ifnull)

select Q.id as id, Q.year as year, ifnull(N.npv,0) as npv
from Queries as Q left join NPV as N on (Q.id = N.id and Q.year = N.year) 

Solution 2: (left join) (coalesce)

select Q.id as id, Q.year as year, coalesce(N.npv,0) as npv
from Queries as Q left join NPV as N on (Q.id = N.id and Q.year = N.year) 

1809. Ad-Free Sessions

image

image

SELECT distinct session_id
FROM playback pb LEFT JOIN ads ad
ON pb.customer_id = ad.customer_id
AND ad.timestamp BETWEEN start_time and end_time
WHERE ad.customer_id IS NULL

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published