SQL Interview Questions
SQL Interview Questions
Products
PRODUCT_ID PRODUCT_NAME
100 NOKIA
200 IPHONE
300 SAMSUNG
Sales
1. Write a SQL query to find the products which have continuous increase in sales every year?
from (
Sales )s )s1
Group by product_id
2. Write a SQL query to find the products which does not have sales at all?
Products t1
Left Join
(Select product_id ,sum(total_sales)
group by product_id
having sum(total_sales)>0
) t2
3. Write a SQL query to find the products whose sales decreased in 2012 compared to 2011?
Join
Products t2
On t1.product_id=t2.product_id
Or
Or
Or
Select * from (
Select p.product_name, year, rank() over (partition by year order by quantity DESC) as rank1
From
Sales s
Join
Product P
On s.product_id=p.product_id
) where rank1=1
1. Write a query to find the products whose quantity sold in a year should be greater than the
average quantity of the product sold across all the years?
Declare @N int;
Set @N=10;
Cte (n)
(
Select 1
Union all
Select n+1 from cte
Where n<=N
)
Select * from cte;
3. Write a query to duplicate each row based on the value in the repeat column? The input table
data looks like as below
Products, Repeat
----------------
A, 3
B, 5
C, 2
Now in the output data, the product A should be repeated 3 times, B should be repeated 5 times
and C should be repeated 2 times. The output will look like as below
Products, Repeat
----------------
A, 3
A, 3
A, 3
B, 5
B, 5
B, 5
B, 5
B, 5
C, 2
C, 2
Cte()
(
Select
Consecutive Available Seats
Several friends at a cinema ticket office would like to reserve consecutive available seats.
Can you help to query all the consecutive available seats order by the seat_id using the following
cinema table?
seat_id free
1 1
2 0
3 1
4 1
5 1
Your query should return the following result for the sample case above.
seat_id
3
4
5
with temp as (
select seat_id,(seat_id-row_number() over(order by seat_id asc)) as diff
from (
(select seat_id from table
where free=1 )t1
),
select order_id,max(minimum_product__id1) as
minimum_product__id1,max(maximum_product__id1) as maximum_product__id1 from (
select order_id,
case when minimum_product__id=1 then product_id else NULL end as minimum_product__id1,
case when maximum_product__id=1 then product_id else NULL end as maximum_product__id1
from (
select *,
row_number() over(partition by order_id order by quantity ASC) as minimum_product__id,
row_number() over(partition by order_id order by quantity DESC
) as maximum_product__id
from
amazon1 )t
where (minimum_product__id=1 or maximum_product__id=1) )t1
group by order_id
restaurant(id,name,address,rating)
orders(order_id,restaurant_id,customer_id,product_id,order_date,amount,customer_rating)
customer(id,name,address,phone_no, zip_code)
asscociate(id,name,restaurat_id,avg_rating)
Questions:
id num
1 1
2 2
3 NULL
4 NULL
5 3
6 NULL
7 4
8 NULL
9 NULL
10 5