GROQ icon indicating copy to clipboard operation
GROQ copied to clipboard

Support sum() as a GROQ function

Open kmelve opened this issue 7 years ago • 6 comments
trafficstars

It would be handy to have the ability to sum numbers in GROQ. The syntax would be similar to count(). It should probably validate that it's a field of the type Number (or just be like JavaScript and sum whatever).

*[_type == 'stats']{
    "pagestats": sum(pageStats[].pageLoads)
}

kmelve avatar Mar 01 '18 07:03 kmelve

Any word on this? Would be super useful for something I'm working on.

coreyward avatar Oct 12 '20 19:10 coreyward

I don't think it should be too hard to do, but I'll leave it to @judofyr to triage it.

kmelve avatar Oct 24 '20 15:10 kmelve

I would also love to see this. Here is an example usecase

Example dataset

{
    "_type":"invoice",
    "request":{
        "_ref":"...",
        "_type:":"reference"
    },
    "items":[
        {
            "itemId":1,
            "price":1000
        },
        {
            "itemId":2,
            "price":2000
        },
        {
            "itemId":3,
            "price":3000
        }
    ]
}

An example query where this would be super usefull

*[_type=="request" && _id == $id]{
    invoices: *[_type=="invoice" && reference(^._id)]{
        "totalPrice": sum(items[].price), // shows the total price of all the items eg; 6000
        items
    }
}[0]

paul-vd avatar Dec 19 '20 13:12 paul-vd

Echoing this, it would be nice to be able to add the up the size fields from the media in order to determine the size of a given group of media:

*[ _type in ["sanity.imageAsset", "sanity.fileAsset"] ]{"totalSize": sum(items[].size)}

KenEucker avatar Nov 15 '21 18:11 KenEucker

any alternatives for the mean time? or do I really need to handle this JS side for now?

yob-yob avatar Mar 20 '22 16:03 yob-yob

any alternatives for the mean time? or do I really need to handle this JS side for now?

We definitely want to add this in the future, but at the moment we don't have a timeline for when it will be available. For now you need to handle this in JS.

judofyr avatar Mar 22 '22 11:03 judofyr

Hi everyone!

We have now launched this functionality as math::sum(), along with a bunch more stuff.

We have also launched a new GROQ spec, which you can read about in our blog: Content is Queryable: (Re)Introducing GROQ.

atombender avatar Sep 15 '22 14:09 atombender