0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SQLでのFizzBuzz

Last updated at Posted at 2023-09-16

さっき、記事にまとめたSQLの書き方で
私なりのfizzbuzzを作るとこんな感じになります。

2025/03/15 追記
もっと楽なSQLがあった。

with seq  as (select  generate_series(1,100,1) as seq)
   , fizzbuzz as (select 3 as num ,'fizz' as str
                        union
                  select 5 as num ,'Buzz' as str)

select seq.seq 
        ,coalesce(string_agg(fizzbuzz.str,'') , seq.seq::text) as FIZZBUZZ
    from seq
    left join fizzbuzz 
              on seq.seq % fizzbuzz.num = 0
group by seq.seq
order by seq.seq
    
with seq as (select generate_series(1,100) as seq)
, fizzbuzz as (select * 
                 from ( values (3,'fizz') 
                              ,(5,'buzz' ) 
                              , (15,'fizzbuzz')) as t (num , text))

select seq.seq
        , coalesce((select text     
                                from fizzbuzz 
                              where seq % num = 0 
                              order by num DESC
                              limit 1)
          ,seq ::text) as fizzbuzz
from seq

image.png

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?