Skip to content

Commit 228d23d

Browse files
committed
SQL: [Docs] Add example for custom bucketing with CASE (#41787)
Add a TIP on how to use CASE to achieve custom bucketing with GROUP BY. Follows: #41349 (cherry picked from commit eb5f5d4)
1 parent 2306531 commit 228d23d

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

docs/reference/sql/functions/conditional.asciidoc

+24
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,30 @@ an error message would be returned, mentioning that *'foo'* is of data type *key
9898
which does not match the expected data type *integer* (based on result *10*).
9999
===============================
100100

101+
[[sql-functions-conditional-case-groupby-custom-buckets]]
102+
===== Conditional bucketing
103+
104+
CASE can be used as a GROUP BY key in a query to facilitate custom bucketing
105+
and assign descriptive names to those buckets. If, for example, the values
106+
for a key are too many or, simply, ranges of those values are more
107+
interesting than every single value, CASE can create custom buckets as in the
108+
following example:
109+
110+
[source, sql]
111+
SELECT count(*) AS count,
112+
CASE WHEN NVL(languages, 0) = 0 THEN 'zero'
113+
WHEN languages = 1 THEN 'one'
114+
WHEN languages = 2 THEN 'bilingual'
115+
WHEN languages = 3 THEN 'trilingual'
116+
ELSE 'multilingual'
117+
END as lang_skills
118+
FROM employees
119+
GROUP BY lang_skills
120+
ORDER BY lang_skills;
121+
122+
With this query, one can create normal grouping buckets for values _0, 1, 2, 3_ with
123+
descriptive names, and every value _>= 4_ falls into the _multilingual_ bucket.
124+
101125
[[sql-functions-conditional-coalesce]]
102126
==== `COALESCE`
103127

docs/reference/sql/language/syntax/commands/select.asciidoc

+4
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,10 @@ Multiple aggregates used:
204204
include-tagged::{sql-specs}/docs/docs.csv-spec[groupByAndMultipleAggs]
205205
----
206206

207+
[TIP]
208+
If custom bucketing is required, it can be achieved with the use of `<<sql-functions-conditional-case, CASE>>`,
209+
as shown <<sql-functions-conditional-case-groupby-custom-buckets, here>>.
210+
207211
[[sql-syntax-group-by-implicit]]
208212
===== Implicit Grouping
209213

0 commit comments

Comments
 (0)