Skip to content

How to use aggregate functions using node js

agershun edited this page Dec 28, 2014 · 3 revisions

How to use aggregate functions using node js?

Source: StackOverflow.com

Question

There is a json which has the array called as chargeamountunitLevel. I want to sum-up the chargeAmount by grouping by the chargeAmountUnit. The Input json:

     "chargeamountunitLevel": [
            {
                "chargeAmount": 4,
                "chargeAmountUnit": "per hour",
                "currencyCode": "USD"
            },
            {
                "chargeAmount": 50,
                "chargeAmountUnit": "per hour",
                "currencyCode": "USD"
            },
            {
                 "chargeAmount": 25,
                 "chargeAmountUnit": "per month",
                 "currencyCode": "USD"
            },
            {
                 "chargeAmount": 25,
                 "chargeAmountUnit": "per month",
                 "currencyCode": "USD"
            }

        ]

The result might be as follows:

        "chargeamountunitLevel": [
            {
                "chargeAmount": 54,
                "chargeAmountUnit": "per hour",
                "currencyCode": "USD"
            },
            {
                 "chargeAmount": 50,
                 "chargeAmountUnit": "per month",
                 "currencyCode": "USD"
            }

            ]

Answer

You can group and aggregate data with Alasql Node.js module. It works in browser and Node.js.

    var alasql = require('alasql');

    var res = alasql('SELECT SUM(chargeAmount) AS chargeAmount, chargeAmountUnit, currencyCode \
           FROM ? GROUP BY chargeAmountUnit, currencyCode',[chargeamountunitLevel ]);

You can try this example (in browser version) in jsFiddle.

To install Alasql npm package use:

    npm install alasql
Clone this wiki locally