Is there having clause in azure cosmos db? How to use it?

▼魔方 西西 提交于 2019-12-12 05:39:45

问题


I was trying to write a query which is finding MAX value from all documents. The scenario is something like I have 100 Students Documents, in which student Name, roll number as well as array of Tests inside that array of Subject and its respective marks. So, I am getting highest marks among subject physics from all documents. But I am not getting it with student roll number. That I was trying to find out.

TestDoc is:

    Student[
    StudenName:"A",
    StudentRollNo :1,
    id:"1",
    StudentAdd:"---",
    Test1:[
    {
      SubName:"S1",
      Marks:20
    },
    {
      SubName:"S2",
      Marks:30
    },
    ...

    ],
    Test2:
    [
     Same as above
    ],         
    ],

    [
    STUDENT2
    ] ,

and so on

Query I am using is: select MAX(s.Marks) from c join test in c.Test1 join s in test.marks


回答1:


According to your description, you want to implement function like GROUP BY in azure cosmosdb queries.

Per my experience, azure cosmosdb aggregation capability in SQL limited to COUNT, SUM, MIN, MAX, AVG functions. GROUP BY or other aggregation functionality are not be supported in azure cosmosdb now.

However, stored procedures or UDF can be used to implement your aggregation requirement.

You could refer to a great package documentdb-lumenize based on DocumentDb stored procedure.

For your first scenario in your post,I created two student documents in my azure cosmosdb account.

[
  {
    "id": "1",
    "StudenName": "A",
    "StudentRollNo": 1,
    "Test": [
      {
        "SubName": "S1",
        "Marks": 20
      },
      {
        "SubName": "S2",
        "Marks": 30
      }
    ],
  },
  {
    "id": "2",
    "StudenName": "B",
    "StudentRollNo": 2,
    "Test": [
      {
        "SubName": "S1",
        "Marks": 10
      },
      {
        "SubName": "S2",
        "Marks": 40
      }
    ],
  }
]

then I put the resultset searched by SQL below to the documentdb-lumenize mentioned above to get the max S2 mark.

SELECT  c.StudentRollNo,test1.Marks as mark FROM c
join test1 in  c.Test
where test1.SubName='S2'

For your second scenario in your comment,I removed the where clause of the SQL above.

SELECT  c.StudentRollNo,test1.Marks as mark FROM c
join test1 in  c.Test

and resultset like:

This applies only to one test.If you want to query multiple tests, you could use stored procedure.

You could also refer to SO threads below:

1.Azure DocumentDB - Group By Aggregates

2.Grouping by a field in DocumentDB



来源:https://stackoverflow.com/questions/46345374/is-there-having-clause-in-azure-cosmos-db-how-to-use-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!