2017-02-09 6 views
0

ハイブにpurchase_dataというテーブルがあり、購入したすべてのリストがあります。
この表を照会して、顧客が購入した最も高価な製品のcust_id、product_id、および価格を調べる必要があります。ハイブ:GROUP BYに存在しない列を取り出すことができません

cust_id   product_id  price purchase_data 
-------------------------------------------------------- 
aiman_sarosh apple_iphone5s 55000 01-01-2014 
aiman_sarosh apple_iphone6s 65000 01-01-2017 
jeff_12   apple_iphone6s 65000 01-01-2017 
jeff_12   dell_vostro  70000 01-01-2017 
missy_el  lenovo_thinkpad 70000 01-02-2017 

私は以下のコードを書かれているが、それは右の行をフェッチしていない:
purchase_dataテーブル内のデータは次のようになります。
いくつかの行が繰り返さなっています

select master.cust_id, master.product_id, master.price 
from 
(
    select cust_id, product_id, price 
    from purchase_data 
) as master 
join 
(
    select cust_id, max(price) as price 
    from purchase_data 
    group by cust_id 
) as max_amt_purchase 
on max_amt_purchase.price = master.price; 

出力:

aiman_sarosh apple_iphone6s 65000.0 
jeff_12   apple_iphone6s 65000.0 
jeff_12   dell_vostro  70000.0 
jeff_12   dell_vostro  70000.0 
missy_el  lenovo_thinkpad 70000.0 
missy_el  lenovo_thinkpad 70000.0 
Time taken: 21.666 seconds, Fetched: 6 row(s) 

は、コードに何か問題はありますか?

答えて

0

使用row_number()

select pd.* 
from (select pd.*, 
      row_number() over (partition by cust_id order by price_desc) as seqnum 
     from purchase_data pd 
    ) pd 
where seqnum = 1; 

これはつながりがあっても、cust_idごとに1つのローを返します。複数の行が必要な場合は、row_number()の代わりにrank()またはdense_rank()を使用します。

+0

おかげ@Gordon、私は、コードを変更し、その作業。私は解決策を掲載しました。 :) – aiman

+0

@aiman。 。 。ランキング機能が実行するときに結合と集約を使用すると、リソースが無駄になり、クエリが複雑になります。 –

0

私は、その、今働いて、コードを変更:

select master.cust_id, master.product_id, master.price 
from 
purchase_data as master, 
(
    select cust_id, max(price) as price 
    from purchase_data 
    group by cust_id 
) as max_price 
where master.cust_id=max_price.cust_id and master.price=max_price.price; 

出力:

aiman_sarosh apple_iphone6s 65000.0 
missy_el  lenovo_thinkpad 70000.0 
jeff_12   dell_vostro  70000.0 

Time taken: 55.788 seconds, Fetched: 3 row(s) 
関連する問題