selectdistinct kk.num as ConsecutiveNums from(select num,count(*) from( select num,row_number() over (orderby id) -row_number() over (partitionby num orderby id) asnew from logs) k groupby num,new havingcount(*)>=3 ) kk
# Write your MySQL query statement below select e1.name as Employee from Employee as e1, Employee as e2 where e1.managerId=e2.id and e1.salary > e2.salary;
# Write your MySQL query statement below select name as Customers from Customers leftjoin Orders on Orders.CustomerId=Customers.id where CustomerId isnull;
select d.name Department,e.name Employee,Salary from Department d leftjoin employee e on e.Departmentid=d.id where (e.Salary,Departmentid) in (selectmax(Salary) Salary,Departmentid from employee groupby Departmentid)
select d.name as Department,k.name as Employee,k.Salary from Department d join (select name, dense_rank() over(partitionby departmentId orderby salary desc) as num,salary,departmentId from employee) k on d.Id=k.departmentId where num between1and3;
# Please write a DELETE statement and DO NOT write a SELECT statement. # Write your MySQL query statement below delete p1.* from Person p1,Person p2 where p1.email=p2.email and p1.id > p2.id;
# Write your MySQL query statement below select w1.id from weather w1,weather w2 where w1.Temperature>w2.Temperature and dateDiff(w1.RecordDate,w2.RecordDate) =1;
select t.request_at asday, round(sum(casewhen status like'cancelled%'then1else0end)/count(*),2) as "Cancellation Rate" from trips t join users u1 on u1.users_id=t.client_id and u1.banned='no' join users u2 on u2.users_id=t.driver_id and u2.banned='no' where request_at between'2013-10-01'and'2013-10-03' groupby request_at;
select player_id,device_id from (select player_id,device_id,dense_rank() over(partitionby player_id orderby event_date asc) dr from activity ) k where dr=1;
select round(count(distinct t.player_id)/(selectcount(distinct player_id) from activity),2) fraction from (select a.player_id, first_value(a.event_date) over(partitionby a.player_id orderby a.event_date) first_date, lead(a.event_date,1) over(partitionby a.player_id orderby a.event_date) next_date from activity a) t where datediff(t.next_date,t.first_date)=1;
select id,company,salary from(select id,company,salary, row_number() over(partitionby company orderby salary) as rnk_asc, count(*) over(partitionby company) as n from employee) k where rnk_asc>=n/2and rnk_asc<=n/2+1;
selectdistinct e.name as name from (select managerid,count(*) over(partitionby managerid) as num from employee) k join employee e where k.managerid=e.id and num>=5;
with temp as( select num,frequency, sum(frequency) over(orderby num asc) s_asc ,sum(frequency) over(orderby num desc) s_desc ,sum(frequency) over() s from numbers ) select round(avg(num),1) as median from temp where s_asc>=s/2and s_desc>=s/2;
select id,month,salary from (select id,month, row_number() over(partitionby e.id orderbymonthdesc) rn, sum(salary) over(partitionby id orderbymonthrange2 preceding) salary from employee e) k where rn>1 orderby id,monthdesc
select dept_name,count(student_id) student_number from Department d leftjoin student a using(dept_id) groupby dept_id orderby student_number desc,dept_name;
select round(sum(tiv_2016),2) tiv_2016 from (select pid,tiv_2016, count(*) over(partitionby tiv_2015) as cnt_2015, count(*) over(partitionby lat,lon ) as city_cnt from insurance)k where cnt_2015>1and city_cnt=1;
select round(ifnull(count(distinct requester_id,accepter_id)/count(distinct sender_id,send_to_id),0),2) as accept_rate from FriendRequest f,RequestAccepted r # on f.sender_id=r.requester_id and f.send_to_id=r.accepter_id
select id,count(*) num from (select requester_id as id from RequestAccepted unionall select accepter_id as id from RequestAccepted) k groupby id orderby num desc limit 1
with k as (select seat_id,seat_id-row_number() over() as x from cinema wherefree=1) select seat_id from k where x in (select x from k groupby x havingcount(*)>=2) orderby seat_id ;
select SalesPerson.name from SalesPerson where sales_id notin (select sales_id from Orders where com_id in (select com_id from Company where name='RED'));
selectmax(casewhen continent='America'then name end) as America, max(casewhen continent='Asia'then name end) as Asia, max(casewhen continent='Europe'then name end) as Europe from (select*,row_number() over(partitionby continent orderby name) rn from student)k groupby rn
selectcase whenmod(id,2)=1and id=s.max then id whenmod(id,2)=0then id-1 else id+1endas id,student from (selectcount(*) max from seat) s,seat orderby id;
# Write your MySQL query statement below select customer_id from product p leftjoin customer c on p.product_key=c.product_key groupby customer_id havingcount(distinct c.product_key)=(selectcount(*) from product);
# Write your MySQL query statement below with a as( select product_id,min(year) as first_year from sales groupby product_id ) select a.product_id,first_year,quantity,price from a leftjoin sales s on a.product_id=s.product_id and a.first_year=s.year
selectdistinct project_id, round(avg( experience_years) over(partitionby project_id),2) as average_years from project p leftjoin employee e using(employee_id)
select project_id,employee_id from ( select project_id,employee_id, rank() over(partitionby project_id orderby experience_years desc) as r from project p join employee e using(employee_id) )k where r=1
select p.product_id,product_name from sales s join product p # on s.product_id=p.product_id using (product_id) groupby product_id havingsum(sale_date<'2019-01-01')=0andsum(sale_date>'2019-03-31')=0;
select install_dt, count(temp.player_id) installs, round(count(a.event_date)/count(install_dt),2) Day1_retention from ( selectmin(event_date) install_dt,player_id from activity groupby player_id )temp leftjoin activity a on a.player_id=temp.player_id and datediff(event_date,install_dt)=1 groupby install_dt
select b.book_id,name from books b leftjoin orders o on b.book_id=o.book_id and dispatch_date>='2018-06-23' where available_from<'2019-05-23' groupby book_id having ifnull(sum(quantity),0)<10
with t as( select student_id,course_id, rank() over(partitionby student_id orderby grade desc,course_id) r,grade from enrollments ) select student_id,course_id,grade from t where r=1 # limit 1 # orderby student_id
select extra report_reason,count(distinct post_id) report_count from actions where action_date='2019-07-04'and extra isnotnulland action='report' groupby extra
with temp as( selectcount(distinct r.post_id)/count(distinct a.post_id)*100aspercent from actions a leftjoin removals r using(post_id) where extra='spam' groupby action_date ) select round(avg(percent),2) average_daily_percent from temp
select ifnull(round(cnt/people,2),0) as average_sessions_per_user from (select user_id,activity_type, count(distinct session_id) as cnt, count(distinct user_id) people from activity where datediff('2019-07-27',activity_date)<30) k
select u.user_id buyer_id,join_date,ifnull(count(order_id),0) as orders_in_2019 from users u leftjoin orders o on u.user_id=o.buyer_id andyear(order_date)=2019 groupby user_id;
# Write your MySQL query statement below select id, sum(if(month='Jan',revenue,null)) as Jan_Revenue, sum(if(month='Feb',revenue,null)) as Feb_Revenue, sum(if(month='Mar',revenue,null)) as Mar_Revenue, sum(if(month='Apr',revenue,null)) as Apr_Revenue, sum(if(month='May',revenue,null)) as May_Revenue, sum(if(month='Jun',revenue,null)) as Jun_Revenue, sum(if(month='Jul',revenue,null)) as Jul_Revenue, sum(if(month='Aug',revenue,null)) as Aug_Revenue, sum(if(month='Sep',revenue,null)) as Sep_Revenue, sum(if(month='Oct',revenue,null)) as Oct_Revenue, sum(if(month='Nov',revenue,null)) as Nov_Revenue, sum(if(month='Dec',revenue,null)) as Dec_Revenue from Department groupby id;
select query_name, round(avg(rating/position),2) as quality, round(sum(casewhen rating<3then1else0end)/count(*)*100,2) as poor_query_percentage from queries groupby query_name
selectdistinct s1.sub_id as post_id,count(distinct s2.sub_id) as number_of_comments from submissions s1 leftjoin submissions s2 on s1.sub_id=s2.parent_id where s1.parent_id isnull groupby post_id orderby post_id
select p.product_id,round(sum(price*units)/sum(units),2) as average_price from unitssold u join prices p on u.product_id=p.product_id and purchase_date between start_date and end_date groupby product_id
select e.employee_id from employees e,employees e1,employees e2 where e1.employee_id=e.manager_id and e2.employee_id=e1.manager_id and e.employee_id<>1and e2.manager_id=1
# Write your MySQL query statement below select st.student_id,student_name,su.subject_name,ifnull(count(e.student_id),0) as attended_exams from subjects su join students st leftjoin examinations e # using(student_id,subject_name) on st.student_id=e.student_id and e.subject_name=su.subject_name groupby st.student_id,su.subject_name orderby st.student_id,su.subject_name
# Write your MySQL query statement below select ad_id, ifnull(round(sum(action='clicked')/sum(action<>'ignored')*100,2),0.00) as ctr from ads groupby ad_id orderby ctr desc,ad_id asc
select product_name,sum(unit) unit from orders leftjoin products using(product_id) where order_date like'2020-02%' groupby product_id havingsum(unit)>=100
with t as( select customer_id,customer_name, ifnull(count(contact_name) over(partitionby customer_id),0) as contacts_cnt, sum(casewhen contact_email in (select email from customers) then1else0end) over(partitionby con.user_id) as trusted_contacts_cnt from customers cus leftjoin contacts con on cus.customer_id=con.user_id ) select invoice_id,customer_name, price,contacts_cnt,trusted_contacts_cnt from invoices i leftjoin t on t.customer_id=i.user_id groupby invoice_id,price orderby invoice_id
select stock_name, sum(casewhen operation='buy'then-price when operation='sell'then price elsenullend) as capital_gain_loss from stocks groupby stock_name;
select c.customer_id,customer_name from customers c join orders o using(customer_id) groupby o.customer_id havingsum(product_name='A')>0andsum(product_name="B")>0andsum(product_name='C')=0
select left_operand,operator,right_operand, casewhen operator='='and a1.value=a2.value then'true' when operator='>'and a1.value>a2.value then'true' when operator='<'and a1.value<a2.value then'true' else'false'endasvalue from expressions e leftjoin variables a1 on a1.name=left_operand leftjoin variables a2 on a2.name=right_operand
select a.id,a.name from (selectdistinct id from( select id,login_date, dense_rank() over(partitionby id orderby login_date) dr from logins l ) t groupby t.id,date_add(login_date,interval-dr day) havingcount(distinct login_date)>=5 ) k
selectdistinct title from content leftjoin tvprogram using(content_id) where program_date like'2020-06%' and content_type='movies' and kids_content='Y'
with temp as( select id,p.phone_number,country_code,c.name country,duration from person p join country c,calls whereleft(p.phone_number,3)=c.country_code and (calls.caller_id=p.id or p.id=calls.callee_id) )
selectdistinct country from (select country,avg(duration) over(partitionby country) c_avg, avg(duration) over() all_avg from temp) k
with temp as( select p.product_id,price,quantity,customer_id,order_date from orders leftjoin product p using(product_id) where order_date between'2020-06-01'and'2020-07-31' groupby customer_id,month(order_date) havingsum(price*quantity)>=100
with t as( select order_id,product_id,order_date, rank() over(partitionby product_id orderby order_date desc) as r from orders ) selectdistinct product_name,t.product_id,order_id,order_date from t join products using(product_id) where r=1 orderby product_name,product_id,order_id
with ot as( select product_id,customer_id, rank() over(partitionby customer_id orderbycount(product_id)desc)r from orders groupby customer_id,product_id ) select ot.customer_id,ot.product_id,p.product_name from ot leftjoin products p on p.product_id=ot.product_id where r=1
select seller_name from seller s leftjoin orders o on s.seller_id=o.seller_id andyear(sale_date)='2020' groupby s.seller_id havingcount(order_id)=0 orderby seller_name
withrecursive t as( select1as n unionall select n+1from t where n<100 ) select n ids from t where n notin(select customer_id from customers) and n<=(selectmax(customer_id) from customers)
select s1.student_name as member_A, s2.student_name as member_B, s3.student_name as member_C from SchoolA s1, SchoolB s2, SchoolC s3 where s1.student_name!=s2.student_name and s1.student_name!=s3.student_name and s2.student_name!=s3.student_name and s1.student_id!=s2.student_id and s1.student_id!=s3.student_id and s2.student_id!=s3.student_id
# Write your MySQL query statement below select machine_id, round(avg(if(activity_type='start',-timestamp,timestamp))*2,3) as processing_time from activity groupby machine_id
# Write your MySQL query statement below select date_id,make_name, count(distinct lead_id) as unique_leads, count(distinct partner_id) as unique_partners from DailySales groupby date_id,make_name;
selectcasewhen from_id<to_id then from_id else to_id end person1, casewhen from_id>to_id then from_id else to_id end person2, count(*) call_count, sum(duration) total_duration from calls groupby person1,person2
with t as ( select*,lead(visit_date,1,'2021-01-01') over(partitionby user_id orderby visit_date) lead_date from uservisits ) select user_id,max(datediff(lead_date,visit_date)) biggest_window from t groupby user_id
selectsum(b.apple_count)+ifnull(sum(c.apple_count),0) apple_count, sum(b.orange_count)+ifnull(sum(c.orange_count),0) orange_count from boxes b leftjoin chests c using(chest_id)
# Write your MySQL query statement below select e1.reports_to as employee_id, e2.name, count(distinct e1.employee_id) as reports_count, round(avg(e1.age),0) as average_age from employees e1,employees e2 where e1.reports_to=e2.employee_id and e1.reports_to isnotnull groupby e1.reports_to orderby e1.reports_to
select player_id,player_name, sum(wimbledon=player_id)+sum(Fr_open=player_id)+sum(US_open=player_id)+sum(Au_open=player_id) as grand_slams_count from players,championships groupby player_id,player_name having grand_slams_count>0
# Write your MySQL query statement below select employee_id,department_id from employee groupby employee_id havingcount(*)=1 union select employee_id,department_id from employee where primary_flag='Y'
select product_id,'store1' store,store1 as price from Products where store1 isnotnull union select product_id,'store2' store,store2 as price from Products where store2 isnotnull union select product_id,'store3' store,store3 as price from Products where store3 isnotnull;
with ktable as( select contest_id,gold_medal user_id from contests unionall select contest_id,silver_medal user_id from contests unionall select contest_id,bronze_medal user_id from contests )
selectdistinct name,mail from users leftjoin ktable using(user_id) where user_id in ( select gold_medal from contests groupby gold_medal havingcount(gold_medal)>=3 union select t2.user_id from( select user_id, contest_id-row_number() over(partitionby user_id orderby contest_id asc) as tag from ktable )t2 groupby user_id,tag havingcount(*)>=3 )
# Write your MySQL query statement below select transaction_id from (select transaction_id,rank() over(partitionby date_format(day,'%y-%m-%d') orderby amount desc)rr from transactions )k where rr=1 orderby transaction_id
selectdistinct order_id from ordersdetails groupby order_id havingmax(quantity)>(selectavg(quantity) a from ordersdetails groupby order_id orderby a desc limit 1)
select user_id,round(ifnull(sum(action='confirmed')/count(*),0),2) confirmation_rate from signups s leftjoin confirmations c using(user_id) groupby user_id
selectdistinct user_id from (select user_id, count(*) over(partitionby user_id orderby time_stamp rangebetweeninterval24hour preceding andcurrentrow) as cnt from confirmations) k where cnt>=2
select Employees.employee_id from Employees leftjoin Salaries using(employee_id) where salary isnull union select Salaries.employee_id from Salaries leftjoin Employees using(employee_id) where name isnull
selectcount(*) accounts_count from subscriptions a join streams b using(account_id) where start_date<='2021-12-31'and end_date>='2021-01-01' and account_id in (select account_id from streams whereyear(stream_date )!=2021)
# Write your MySQL query statement below select candidate_id from candidates leftjoin rounds using(interview_id) where years_of_exp>=2 groupby interview_id havingsum(score)>15
with a as( select member_id,count(visit_id) over(partitionby member_id) as visit_cnt,sum(charged_amount isnotnull) over(partitionby member_id) purchase_cnt from visits leftjoin purchases using(visit_id) ) select member_id,name, casewhen100*purchase_cnt/visit_cnt>=80then'Diamond' when100*purchase_cnt/visit_cnt>=50and100*purchase_cnt/visit_cnt<80then'Gold' when100*purchase_cnt/visit_cnt<50then'Silver' else'Bronze'endas category from members m leftjoin a using(member_id) groupby member_id
with k as( selectsum(n.score>=90) as ng,sum(c.score>=90) as cg from newyork n,california c ) selectcasewhen ng>cg then'New York University' when ng<cg then'California University' else'No Winner'endas winner from k
with t as( select departure_airport airport_id,flights_count from flights unionall select arrival_airport airport_id,flights_count from flights ) select airport_id from (select airport_id,rank() over(orderbysum(flights_count) desc) r from t groupby airport_id ) tt where r=1
CREATEFUNCTION getUserIDs(startDate DATE, endDate DATE, minAmount INT) RETURNSINT BEGIN RETURN ( selectcount(distinct user_id) from purchases where (time_stamp between startdate and enddate) and amount>=minAmount ); END
CREATEPROCEDURE getUserIDs(startDate DATE, endDate DATE, minAmount INT) BEGIN selectdistinct user_id from purchases where (time_stamp between startDate and endDate) and amount>=minAmount orderby user_id;
# Write your MySQL query statement below with a as( select*, row_number() over(partitionby gender orderby user_id) rn from genders ) select user_id,gender from (select user_id,gender, casewhen gender='female'then rn when gender='other'then rn+0.5 else rn+0.6endas r from a)aa orderby r,user_id
with k as( select user_id, product_id, rank() over(partitionby user_id orderbysum(price*quantity) desc) r from sales s leftjoin product p using(product_id) groupby s.user_id,s.product_id )
with a as( select student_id,department_id, rank() over(partitionby department_id orderby mark desc) r, count(student_id) over(partitionby department_id) cnt from students ) select student_id,department_id,round(ifnull((r-1)*100/(cnt-1),0),2) percentage from a
# Write your MySQL query statement below selectdistinct sp.salesperson_id,name,ifnull(sum(price) over(partitionby sp.salesperson_id),0) total from salesperson sp leftjoin customer c on sp.salesperson_id=c.salesperson_id leftjoin sales s on c.customer_id=s.customer_id
# Write your MySQL query statement below select* from olympic groupby country orderbymax(gold_medals)desc,max(silver_medals)desc,max(bronze_medals)desc,country
with a as( select employee_id,sum(ceiling(timestampdiff(second,in_time,out_time)/60))/60 s from logs groupby employee_id ) select employee_id from employees leftjoin a using(employee_id) where s<needed_hours or s isnull