From eb48b3559712c1eb6cfb35663daf37437b4aba33 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 27 Jun 2015 11:00:38 -0500 Subject: [PATCH] Add Fizzbuzz With Common Table Expressions as a postgres til. --- README.md | 1 + .../fizzbuzz-with-common-table-expressions.md | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 postgres/fizzbuzz-with-common-table-expressions.md diff --git a/README.md b/README.md index 989ab8c..0914ba4 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ smart people at [Hashrocket](http://hashrocket.com/). - [Count Records By Type](postgres/count-records-by-type.md) - [Default Schema](postgres/default-schema.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) - [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) diff --git a/postgres/fizzbuzz-with-common-table-expressions.md b/postgres/fizzbuzz-with-common-table-expressions.md new file mode 100644 index 0000000..a694cce --- /dev/null +++ b/postgres/fizzbuzz-with-common-table-expressions.md @@ -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; +```