q11.sql 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. c_preferred_cust_flag customer_preferred_cust_flag,
  7. c_birth_country customer_birth_country,
  8. c_login customer_login,
  9. c_email_address customer_email_address,
  10. d_year dyear,
  11. sum(ss_ext_list_price - ss_ext_discount_amt) year_total,
  12. 's' sale_type
  13. FROM customer, store_sales, date_dim
  14. WHERE c_customer_sk = ss_customer_sk
  15. AND ss_sold_date_sk = d_date_sk
  16. GROUP BY c_customer_id
  17. , c_first_name
  18. , c_last_name
  19. , d_year
  20. , c_preferred_cust_flag
  21. , c_birth_country
  22. , c_login
  23. , c_email_address
  24. , d_year
  25. UNION ALL
  26. SELECT
  27. c_customer_id customer_id,
  28. c_first_name customer_first_name,
  29. c_last_name customer_last_name,
  30. c_preferred_cust_flag customer_preferred_cust_flag,
  31. c_birth_country customer_birth_country,
  32. c_login customer_login,
  33. c_email_address customer_email_address,
  34. d_year dyear,
  35. sum(ws_ext_list_price - ws_ext_discount_amt) year_total,
  36. 'w' sale_type
  37. FROM customer, web_sales, date_dim
  38. WHERE c_customer_sk = ws_bill_customer_sk
  39. AND ws_sold_date_sk = d_date_sk
  40. GROUP BY
  41. c_customer_id, c_first_name, c_last_name, c_preferred_cust_flag, c_birth_country,
  42. c_login, c_email_address, d_year)
  43. SELECT t_s_secyear.customer_preferred_cust_flag
  44. FROM year_total t_s_firstyear
  45. , year_total t_s_secyear
  46. , year_total t_w_firstyear
  47. , year_total t_w_secyear
  48. WHERE t_s_secyear.customer_id = t_s_firstyear.customer_id
  49. AND t_s_firstyear.customer_id = t_w_secyear.customer_id
  50. AND t_s_firstyear.customer_id = t_w_firstyear.customer_id
  51. AND t_s_firstyear.sale_type = 's'
  52. AND t_w_firstyear.sale_type = 'w'
  53. AND t_s_secyear.sale_type = 's'
  54. AND t_w_secyear.sale_type = 'w'
  55. AND t_s_firstyear.dyear = 2001
  56. AND t_s_secyear.dyear = 2001 + 1
  57. AND t_w_firstyear.dyear = 2001
  58. AND t_w_secyear.dyear = 2001 + 1
  59. AND t_s_firstyear.year_total > 0
  60. AND t_w_firstyear.year_total > 0
  61. AND CASE WHEN t_w_firstyear.year_total > 0
  62. THEN t_w_secyear.year_total / t_w_firstyear.year_total
  63. ELSE NULL END
  64. > CASE WHEN t_s_firstyear.year_total > 0
  65. THEN t_s_secyear.year_total / t_s_firstyear.year_total
  66. ELSE NULL END
  67. ORDER BY t_s_secyear.customer_preferred_cust_flag
  68. LIMIT 100