Mnesia "group by" || fold/3 -
06-14-2011
, 04:19 AM
Hello!
I would like to ask for help in finding the equivalent of "group by"
(from SQL) in Mnesia.
I found QLC:fold/3 (QLC:fold/4) and start work with it.... but must be
simpler way to do this ;-)
I have some test data build on:
-record(hobby,{id,day,hour,lake,fish,count}).
mnesia:create_table(hobby, [{attributes, record_info(fields,hobby)},
{disc_copies, [node()]}]).
How can I do something like:
SELECT
DAY, HOUR, COUNT(*)
FROM HOBBY
GROUP BY DAY HOUR;
%I try to get data:
get_fish_day_hour()->
F=fun()->
Q=qlc:q( [ {A#hobby.day,A#hobby.hour, A#hobby.count} || A<-
mnesia:table(hobby) ] ),
%qlc:e( Q )
qlc:fold(fun act_aggregate_d_h/2, dict:new(), Q)
end,
{atomic,LST}=mnesia:transaction( F ),
LST.
%and do the aggregation magic:
act_aggregate_d_h({Day,Hour,Count},Dict)->
case dict:is_key(Day,Dict) of
true ->
D_Dict=dict:fetch(Day,Dict),
case dict:is_key(Hour,D_Dict) of
true ->
D_new_Dict=dict:update(Hour,fun(Sum)->Sum + Count end,D_Dict),
dict:update(Day,fun(Sum)->D_new_Dict end,Dict);
false ->
D_new_Dict=dict:append(Hour,fun(Sum)->Count end,D_Dict),
dict:update(Day,fun(Sum)->D_new_Dict end,Dict)
end;
false ->
D_new_Dict=dict:append(Hour,Count,dict:new()),
dict:append(Day,D_new_Dict,Dict)
end.
....and it of corse dosent working :-((.
....but when I look on this I dont bealive that there isn't existing
simpler way to do that basic thing.
Could you help me ? |