2014-12-19 96 views
1

工會不同的值我有一個蜂巢表看起來像這樣獲取所有在蜂巢

cust_id prod_id timestamp 
1  11  2011-01-01 03:30:23 
2  22  2011-01-01 03:34:53 
1  22  2011-01-01 04:21:03 
2  33  2011-01-01 04:44:09 
3  33  2011-01-01 04:54:49 

等等等等。

因爲我要檢查有多少獨特的產品有這個客戶過去的24個小時,不包括當前事務中買了每個記錄。所以輸出應該是這個樣子 -

1  0 
2  0 
1  1 
2  1 
3  0 

我的蜂巢查詢看起來像這樣

select * from(
select t1.cust_id, count(distinct t1.prod_id) as freq from temp_table t1 
left outer join temp_table t2 on (t1.cust_id=t2.cust_id) 
where t1.timestamp>=t2.timestamp 
and unix_timestamp(t1.timestamp)-unix_timestamp(t2.timestamp) < 24*60*60 
group by t1.cust_id 
union all 
select t.cust_id, 0 as freq from temp_table t2 
)unioned; 
+0

什麼意思是「不包括當前交易」?你的意思是「最新的交易」? – Nonnib 2014-12-19 08:46:10

回答

0

東西剛拿到的所有行過去24小時對客戶ID做1組和計數(不同的productid )-1作爲輸出。總體查詢看起來像這樣。

選擇的cust_id,COUNT(DISTINCT PROD_ID) - 從表名其中 UNIX_TIMESTAMP(t1.timestamp)-unix_timestamp(t2.timestamp)< 24 * 60 * 60 GROUP BY CUST_ID

1 *我在這裏減1以排除用戶的最新的transactionid。 (希望這是你的意思)

0

你可以加入到包含在過去24小時內爲每一個客戶/時間戳對所購產品的不同#派生表。

select t1.cust_id, t1.prod_id, t1.timestamp, t2.count_distinct_prod_id - 1 
from mytable t1 
join (
    select t2.cust_id, t2.timestamp, count(distinct t3.prod_id) count_distinct_prod_id 
    from mytable t2 
    join mytable t3 on t3.cust_id = t2.cust_id 
    where unix_timestamp(t2.timestamp) - unix_timestamp(t3.timestamp) < 24*60*60 
    group by t2.cust_id, t2.timestamp 
) t2 on t1.cust_id = t2.cust_id and t1.timestamp = t2.timestamp