私のテーブル構造はこれに似ています
Customer_id Country item_type Order_Size Dates Codes
A401 US Fruit Small 3/14/2016 11
A401 US Fruit Big 5/22/2016 12
A401 US Vegetable Small 7/12/2016 11
B509 US Vegetable Small 3/25/2015 92
B509 US Vegetable Big 3/15/2014 11
B509 US Vegetable Small 3/1/2014 34
A402 CA Fruit Small 3/14/2016 56
A402 CA Fruit Big 5/22/2016 76
A402 CA Fruit Small 7/12/2016 85
A403 CA Vegetable Small 7/12/2016 11
A403 CA Vegetable Small 3/25/2015 16
A403 CA Vegetable Big 3/15/2014 17
A403 CA Vegetable Small 3/1/2014 12
Order_size = Big を購入し、order_size <> Big で購入したアイテムのみを購入した後にのみ、 item_type ごとに何人のリピート顧客が存在するかを国ごとに調べています。これを達成するために、私はこのコードを書きました。
SELECT Country,item_type,count(customer_id) from
(select Country,customer_id, t.item_type, count(*) as REPEATS
from (select t.*,
min(case when Order_Size = 'Big' then dates end) over (partition by customer_id, item_type) as min_big
from data_test as t
) t
where dates > min_big
group by 1,2,3) D
group by 1,2
結果:
Country item_type Count(Distinct(Customer_id))
CA Vegetable 1
US Vegetable 1
CA Fruit 1
これで機能しますが、コードが条件付きの特定のテーブル内にある場合にのみ条件をもう 1 つ追加したかったので、コードを変更したときにサブクエリを 1 つ含む複数の条件を追加したかったのです。
SELECT Country,item_type,count(customer_id) from
(select Country,customer_id, t.item_type, count(*) as REPEATS
from (select t.*,
min(case when (Order_Size = 'Big' and Codes IN (SELECT CODES from table1 where type='TRUE' group by 1)) then dates end) over (partition by customer_id, item_type) as min_big
from data_test as t
) t
where dates > min_big
group by 1,2,3) D
group by 1,2
これはエラーをスローしています - case ステートメント内の When 句の式が不正です。また、ケース内でサブクエリを使用できず、INも使用できないことも読みました。これに関連する他の多くの質問を読みましたが、サブクエリの使用を回避する方法についてはまだ明確ではありません。テーブルが非常に大きいため、エラーをスローせず、高速に処理できるコードを変更するにはどうすればよいですか?