mirror of
https://github.com/jbranchaud/til
synced 2026-01-16 13:38:02 +00:00
Add Fizzbuzz With Common Table Expressions as a postgres til.
This commit is contained in:
@@ -59,6 +59,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
|||||||
- [Count Records By Type](postgres/count-records-by-type.md)
|
- [Count Records By Type](postgres/count-records-by-type.md)
|
||||||
- [Default Schema](postgres/default-schema.md)
|
- [Default Schema](postgres/default-schema.md)
|
||||||
- [Extracting Nested JSON Data](postgres/extracting-nested-json-data.md)
|
- [Extracting Nested JSON Data](postgres/extracting-nested-json-data.md)
|
||||||
|
- [Fizzbuzz With Common Table Expressions](postgres/fizzbuzz-with-common-table-expressions.md)
|
||||||
- [Generate Series Of Numbers](postgres/generate-series-of-numbers.md)
|
- [Generate Series Of Numbers](postgres/generate-series-of-numbers.md)
|
||||||
- [Limit Execution Time Of Statements](postgres/limit-execution-time-of-statements.md)
|
- [Limit Execution Time Of Statements](postgres/limit-execution-time-of-statements.md)
|
||||||
- [List All Columns Of A Specific Type](postgres/list-all-columns-of-a-specific-type.md)
|
- [List All Columns Of A Specific Type](postgres/list-all-columns-of-a-specific-type.md)
|
||||||
|
|||||||
23
postgres/fizzbuzz-with-common-table-expressions.md
Normal file
23
postgres/fizzbuzz-with-common-table-expressions.md
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
# Fizzbuzz With Common Table Expressions
|
||||||
|
|
||||||
|
In learning about CTEs (common table expressions) in postgres, I discovered
|
||||||
|
that you can do some interesting and powerful things using the `with
|
||||||
|
recursive` construct. The following solves the fizzbuzz problem for integers
|
||||||
|
up to 100
|
||||||
|
|
||||||
|
```sql
|
||||||
|
with recursive fizzbuzz (num,val) as (
|
||||||
|
select 0, ''
|
||||||
|
union
|
||||||
|
select (num + 1),
|
||||||
|
case
|
||||||
|
when (num + 1) % 15 = 0 then 'fizzbuzz'
|
||||||
|
when (num + 1) % 5 = 0 then 'buzz'
|
||||||
|
when (num + 1) % 3 = 0 then 'fizz'
|
||||||
|
else (num + 1)::text
|
||||||
|
end
|
||||||
|
from fizzbuzz
|
||||||
|
where num < 100
|
||||||
|
)
|
||||||
|
select val from fizzbuzz where num > 0;
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user