Stan Smith
Stan Smith

Reputation: 45

Sql Query Solution Check

I feel stupid asking this question because it seems relatively easy. Okay, I interviewed with a company today and got asked the below SQL query question, I think I provided the right query but the interviewer wasn't impressed at all. I came back to my local system and produced similar data with my query. I cant think of what's wrong with it. What do you all think, is this a wrong solution? -Thanks for reading this!

QUESTION:

Find the total no of products for each store which had more than one block in 2020

store_id complaint_day action_day product_id action_type
1 2019-12-20 2020-01-01 1A block
1 2019-12-20 2020-01-02 1A reinstate
1 2019-12-22 2020-01-03 1A block
3 2019-12-20 2020-01-03 2B block
3 2019-12-20 2020-01-03 1A block
4 2019-12-03 2020-01-04 2C block
; with cte as
(
select 1 as 'store_id', '2020-01-01' as 'action_day' ,'1A' as product_id, 'block' as 'action_type' Union all
select 1 , '2020-01-01', '1A' , 'reinstate'  Union all
select 1 , '2020-01-02', '1A' , 'block' Union all
select 3 , '2020-01-03', '2B' , 'block' Union all
select 3 , '2020-01-03', '1A' , 'block' Union all
select 4 , '2020-01-04', '2C' , 'block' 
)

Select store_id, count( product_id) as total from cte
where action_type = 'block' and year(action_Day) = 2020
group by store_id
having count(product_id) >1

Upvotes: 0

Views: 140

Answers (1)

itsmetonton
itsmetonton

Reputation: 56

This is how i understood the question. You are looking for the number of products on a store with more than 1 block.

;with cte as
(
select 1 as 'store_id', '2020-01-01' as 'action_day' ,'1A' as product_id, 'block' as 'action_type' Union all
select 1 , '2020-01-01', '1A' , 'reinstate'  Union all
select 1 , '2020-01-02', '1A' , 'block' Union all
select 3 , '2020-01-03', '2B' , 'block' Union all
select 3 , '2020-01-03', '1A' , 'block' Union all
select 4 , '2020-01-04', '2C' , 'block' 
)

SELECT 
action_type
,product_id
,store_id
,COUNT(1) as block_count
FROM cte
where action_type = 'block' and year(action_Day) = 2020
GROUP BY action_type,product_id,store_id
HAVING COUNT(1) > 1

Upvotes: 1

Related Questions