sql - Mysql sum from another table -


i've got database every user has uid, can login different nickname each time (table a). user can buy stuff , and saving login id , price (table b). made example, note nick , nickrenamed same person have same uid

table a

id  |  nickname   |  uid 1   | nick        |  abcdef 2   | nack        |  ab1234 3   | nickrenamed |  abcdef 

table b

id  |  ida  | price 1   |   1   |   200 2   |   1   |   400 3   |   2   |    20 4   |   3   |    75 

for statistic want every (distinct) uid, latest nickname , sum price of user

uid    | nickname    |  price_total abcdef | nickrenamed |   675 ac1234 | nack        |    20 

my approch

select distinct(a.uid)      , a.id      , a.nickname      , sum(b.price)       join b      on a.id = b.ida   group      a.uid 

but error gets thrown

expression #2 of select list not in group clause , contains nonaggregated  column 'test.a.id' not functionally dependent on columns in  group clause; incompatible sql_mode=only_full_group_by 

you need 2 separated queries that.

first find out sum of each user

select uid, sum(price) total tablea ta join tableb tb   on ta.id = tb.ida group uid 

now latest name of each user.

select nickname, uid tablea t1 left join tablea t2   on t1.id > t2.id  , t1.uid = t2.uid t2.id null 

now put both together

 select step1.uid,          step2.nickname,         step1.total   (    select uid, sum(price) total            tablea ta            join tableb tb              on ta.id = tb.ida            group uid) step 1  join (    select nickname, uid            tablea t1            left join tablea t2              on t1.id > t2.id             , t1.uid = t2.uid            t2.id null ) step2   on step1.uid = step2.uid 

Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -