tpch_query21.sql 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. drop view q21_tmp1_cached;
  2. drop view q21_tmp2_cached;
  3. create view q21_tmp1_cached as
  4. select
  5. l_orderkey,
  6. count(distinct l_suppkey) as count_suppkey,
  7. max(l_suppkey) as max_suppkey
  8. from
  9. lineitem
  10. where
  11. l_orderkey is not null
  12. group by
  13. l_orderkey;
  14. create view q21_tmp2_cached as
  15. select
  16. l_orderkey,
  17. count(distinct l_suppkey) count_suppkey,
  18. max(l_suppkey) as max_suppkey
  19. from
  20. lineitem
  21. where
  22. l_receiptdate > l_commitdate
  23. and l_orderkey is not null
  24. group by
  25. l_orderkey;
  26. select
  27. s_name,
  28. count(1) as numwait
  29. from (
  30. select s_name from (
  31. select
  32. s_name,
  33. t2.l_orderkey,
  34. l_suppkey,
  35. count_suppkey,
  36. max_suppkey
  37. from
  38. q21_tmp2_cached t2 right outer join (
  39. select
  40. s_name,
  41. l_orderkey,
  42. l_suppkey from (
  43. select
  44. s_name,
  45. t1.l_orderkey,
  46. l_suppkey,
  47. count_suppkey,
  48. max_suppkey
  49. from
  50. q21_tmp1_cached t1 join (
  51. select
  52. s_name,
  53. l_orderkey,
  54. l_suppkey
  55. from
  56. orders o join (
  57. select
  58. s_name,
  59. l_orderkey,
  60. l_suppkey
  61. from
  62. nation n join supplier s
  63. on
  64. s.s_nationkey = n.n_nationkey
  65. and n.n_name = 'SAUDI ARABIA'
  66. join lineitem l
  67. on
  68. s.s_suppkey = l.l_suppkey
  69. where
  70. l.l_receiptdate > l.l_commitdate
  71. and l.l_orderkey is not null
  72. ) l1 on o.o_orderkey = l1.l_orderkey and o.o_orderstatus = 'F'
  73. ) l2 on l2.l_orderkey = t1.l_orderkey
  74. ) a
  75. where
  76. (count_suppkey > 1)
  77. or ((count_suppkey=1)
  78. and (l_suppkey <> max_suppkey))
  79. ) l3 on l3.l_orderkey = t2.l_orderkey
  80. ) b
  81. where
  82. (count_suppkey is null)
  83. or ((count_suppkey=1)
  84. and (l_suppkey = max_suppkey))
  85. ) c
  86. group by
  87. s_name
  88. order by
  89. numwait desc,
  90. s_name
  91. limit 100;