q74.sql 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. WITH year_total AS (
  2. SELECT
  3. c_customer_id customer_id,
  4. c_first_name customer_first_name,
  5. c_last_name customer_last_name,
  6. d_year AS year,
  7. sum(ss_net_paid) year_total,
  8. 's' sale_type
  9. FROM
  10. customer, store_sales, date_dim
  11. WHERE c_customer_sk = ss_customer_sk
  12. AND ss_sold_date_sk = d_date_sk
  13. AND d_year IN (2001, 2001 + 1)
  14. GROUP BY
  15. c_customer_id, c_first_name, c_last_name, d_year
  16. UNION ALL
  17. SELECT
  18. c_customer_id customer_id,
  19. c_first_name customer_first_name,
  20. c_last_name customer_last_name,
  21. d_year AS year,
  22. sum(ws_net_paid) year_total,
  23. 'w' sale_type
  24. FROM
  25. customer, web_sales, date_dim
  26. WHERE c_customer_sk = ws_bill_customer_sk
  27. AND ws_sold_date_sk = d_date_sk
  28. AND d_year IN (2001, 2001 + 1)
  29. GROUP BY
  30. c_customer_id, c_first_name, c_last_name, d_year)
  31. SELECT
  32. t_s_secyear.customer_id,
  33. t_s_secyear.customer_first_name,
  34. t_s_secyear.customer_last_name
  35. FROM
  36. year_total t_s_firstyear, year_total t_s_secyear,
  37. year_total t_w_firstyear, year_total t_w_secyear
  38. WHERE t_s_secyear.customer_id = t_s_firstyear.customer_id
  39. AND t_s_firstyear.customer_id = t_w_secyear.customer_id
  40. AND t_s_firstyear.customer_id = t_w_firstyear.customer_id
  41. AND t_s_firstyear.sale_type = 's'
  42. AND t_w_firstyear.sale_type = 'w'
  43. AND t_s_secyear.sale_type = 's'
  44. AND t_w_secyear.sale_type = 'w'
  45. AND t_s_firstyear.year = 2001
  46. AND t_s_secyear.year = 2001 + 1
  47. AND t_w_firstyear.year = 2001
  48. AND t_w_secyear.year = 2001 + 1
  49. AND t_s_firstyear.year_total > 0
  50. AND t_w_firstyear.year_total > 0
  51. AND CASE WHEN t_w_firstyear.year_total > 0
  52. THEN t_w_secyear.year_total / t_w_firstyear.year_total
  53. ELSE NULL END
  54. > CASE WHEN t_s_firstyear.year_total > 0
  55. THEN t_s_secyear.year_total / t_s_firstyear.year_total
  56. ELSE NULL END
  57. ORDER BY 1, 1, 1
  58. LIMIT 100