Couchbase N1QL: GROUP BY CASE clause not working

I think I have the solution you want:

SELECT Hemisphere,
  COUNT(DISTINCT name) AS LandmarkCount
FROM `travel-sample` AS l
LET Hemisphere = CASE
    WHEN l.geo.lon <0 THEN "West"
    ELSE "East"
  END
WHERE type="landmark"
GROUP BY Hemisphere;

The error you’re getting is because in 6.0, AS isn’t supported in GROUP BY (as shown in the 6.0 docs and as the error message says).

An alternative is to use LET in 6.0+ to define a variable, as I did in the above example.

But note that LET is not required either; you could also write your query without it, like this:

SELECT CASE
    WHEN l.geo.lon <0 THEN "West"
    ELSE "East"
  END AS Hemisphere,
  COUNT(DISTINCT name) AS LandmarkCount
FROM `travel-sample` AS l
WHERE type="landmark"
GROUP BY CASE
  WHEN l.geo.lon <0 THEN "West"
  ELSE "East"
END;

But I think you’ll agree that the former is easier to read, understand, and change.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top