Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
915 views
in Technique[技术] by (71.8m points)

c# - OData v4 groupby with $count

I'm using OData v4 with WebAPI with these nuget-packages:

Microsoft.Data.OData 5.7.0

Microsoft.AspNet.WebApi.OData 4.0.30506

I can't get groupby to work with count. It should be the most simple thing.

I have a simple table/entity called Delivery. It has a status column (among several other ones). What I basically want to do is this SQL query, but with OData:

SELECT e.status, count(*) AS total
FROM Delivery e
GROUP BY e.status

I've tried using countdistinct, but it doesn't give me the correct results.

/odata/deliveries?$apply=groupby((status),aggregate(status with countdistinct as total))

It returns:

"value": [
{
    "@odata.id": null,
    "total": 1,
    "status": 1
},
{
    "@odata.id": null,
    "status": 2,
    "total": 1
},
{
    "@odata.id": null,
    "status": 4,
    "total": 1
}
]

The correct results should be (which is what my SQL-query returns):

status  total
1       2
2       22
4       1

I've also read about the virtual property $count, but it seems as Microsoft doesn't support it yet.

How do I use group by together with a simple count with OData v4?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Whilst $count is not supported, contdistinct has been supported for a while and is possibly more syntactically correct for OData aggregate scenarios, the documentation is a little bit lacking but countdistinct gives the caller control over which field to use in the result set to determine the unique results. This is especially useful in complex nested or expanded grouping queries.

So it turns out you have a simple bug in your query!

In your query: /odata/deliveries?$apply=groupby((status),aggregate(status with countdistinct as total))

You are asking for count all the distinct values of status. Because you are grouping by status, the distinct values in each group will always be 1 :)

Your actual query should be to countdistinct over a property that will be unique for each item in the set, usually an Id. Assuming Delivery has an Id field called "Id", your query should be this:

/odata/deliveries?$apply=groupby((status),aggregate(id with countdistinct as total))

this will translate closely to your expected SQL:

SELECT status, COUNT(DISTINCT id) AS total
FROM Delivery
GROUP BY status

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...