Advertisement
david929

kk

Feb 6th, 2022
2,084
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 0.67 KB | None | 0 0
  1. -- A customer is called a commuter if she buys at least 70% of her purchases in stores outside her city.
  2. -- Give an SQL query to find the number of commuter customers by customer city.
  3.  
  4.  
  5. WITH temp AS (SELECT S.store_id, C.city, C.customer_id, SUM(store_sales) AS Tot,
  6.                 SUM(CASE WHEN C.city <> store_city THEN store_sales ELSE 0 END) AS TotFuoriCitta
  7.                 FROM store S, sales_fact AS SL, customer AS C
  8.                 WHERE S.store_id = SL.store_id AND SL.customer_id = C.customer_id
  9.                 GROUP BY S.store_id,C.city, C.customer_id)
  10.  
  11.  
  12. SELECT *, SUM(CASE WHEN 100*TotFuoriCitta/Tot >=70 THEN 1 ELSE 0 END) AS NCust
  13. FROM temp
  14. GROUP BY city
  15.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement