Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to group and count

agershun edited this pageDec 28, 2014 ·2 revisions

How to group and count?

Source:StackOverflow.com

Question

There is an array like this:

[{dep:'A',qt:10,price:5},{dep:'A',qt:5,price:2.30},{dep:'B',qt:3,price:2.20},{dep:'C',qt:1,price:4},{dep:'C',qt:4,price:10}...etc..]

What's the elegant way to both group and sum values, resulting into:

[{dep:'A',qt:15,price:61.5},{dep:'B',qt:3,price:2.20},{dep:'C',qt:5:price:44}]

Answer

You can do it in elegant way:

varres=alasql('SELECT dep, SUM(qt) AS qt, SUM(qt*price) AS amt,AGGR(amt/qt)ASpriceFROM ?GROUPBYdep',[data]);

Try this exampleat jsFiddle.

I changed a little bit the algorithm for calculation of average price based on quantity sold.

© 2014-2026,Andrey Gershun &Mathias Rangel Wulff

Please help improve the documentation by opening a PR on thewiki repo

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp