azure-cosmosdbazure-cosmosdb-sqlapi

How to query Cosmos DB to find SUM of item per different conditions?


This is a sample item in my Cosmos database:

{
    "id": "a683-89e01def5310",
    "assignmentId": "123",
    "auctionSiteId": 100,
    "status": "Scheduled",
...
}

There is no problem when I write this basic query and run it:

SELECT VALUE 
    COUNT(c.id)
FROM 
    c
WHERE 
    c.auctionSiteId = 100 AND c.status = "Scheduled"

I get a proper result. However, I don't when I make it a bit complex to calculate the same thing for multiple sites in one shot. This is my query:

with temp as (
  select c.auctionSiteId from c
  where c.status = "Scheduled"
),
logic as(
  select
    case when c.auctionSiteId = 96 then 1 else 0 end as count_montreal,
    case when c.auctionSiteId = 97 then 1 else 0 end as count_vancouver,
    case when c.auctionSiteId = 98 then 1 else 0 end as count_calgary,
    case when c.auctionSiteId = 99 then 1 else 0 end as count_edmonton,
    case when c.auctionSiteId = 100 then 1 else 0 end as count_toronto,
    
  from temp
)
select
  sum(count_montreal) as countMontreal,
  sum(count_vancouver) as countVancouver,
  sum(count_calgary) as countCalgary,
  sum(count_edmonton) as countEdmonton,
  sum(count_toronto) as countToronto,
from logic

This is the error message I get:

{"code":"BadRequest","message":"One of the input values is invalid.\r\nActivityId: 5a1a98e3-aca1-40b4-8378-6cd5b4ba2bbf, Wind...

Solution

  • SELECT 
        SUM(c.auctionSiteId = 1 ?1:0) AS countMontreal,
        SUM(c.auctionSiteId = 2 ?1:0) AS countVancouver,
        SUM(c.auctionSiteId = 3 ?1:0) AS countCalgary,
        SUM(c.auctionSiteId = 4 ?1:0) AS countEdmonton,
        SUM(c.auctionSiteId = 5 ?1:0) AS countToronto
    FROM c
    WHERE c.status = "Scheduled"
    

    Hope this helps. Cosmos, unlike SQL, does not support case when syntax. Would reccommend using ternary operator instead