2016-04-13 51 views
0

-1到100在SQL中顯示'Fizz'如果數字可以被3整除'Buzz'如果可以被5整除並且'FizzBu​​zz'被兩個整除。下面是我的代碼Fizz嗡嗡聲SQL邏輯錯誤

select 
Case when Remainder (rownum,3)=0 then 'Fizz' 
    when Remainder (rownum,5)=0 then 'Buzz' 
    when (remainder (rownum,3)=0 and remainder(ROWNUM,5) = 0) then 'FizzBuzz' 
    else rownum end 
from DUAL 
Connect by level <=100; 

它給了我錯誤 - ORA-00932:不一致的數據類型:預期CHAR了NUMBER 00932. 00000 - 「不一致的數據類型:有望%S得了%的」 *原因:
*行動: 錯誤在行:5列:18

+1

投的ROWNUM爲VARCHAR2 – Quassnoi

+1

[代碼高爾夫球:1,2, Fizz,4,Buzz](http://codegolf.stackexchange.com/a/58969/15968) – MT0

回答

2

您需要通過要麼ROWNUM轉換爲字符串在ELSE情況:

  • CAST(ROWNUM AS VARCHAR2(3))
  • ''||ROWNUM
  • TO_CHAR(ROWNUM)

您還需要這樣一種情況,即它可以被3和5整除以排在列表的頂部(否則前面的例子將優先)。就像這樣:

SELECT CASE 
     WHEN remainder (rownum,15)=0 THEN 'FizzBuzz' 
     WHEN Remainder (rownum,3)=0 THEN 'Fizz' 
     WHEN Remainder (rownum,5)=0 THEN 'Buzz' 
     ELSE TO_CHAR(rownum) 
     END 
FROM DUAL 
CONNECT BY LEVEL <= 100; 

不過,可以縮短代碼有很多(從一個答案我張貼Code Golf拍攝):

SELECT NVL(
     DECODE(MOD(LEVEL,3),0,'Fizz')||DECODE(MOD(LEVEL,5),0,'Buzz'), 
     ''||LEVEL 
     ) 
FROM DUAL 
CONNECT BY LEVEL<101 
+0

非常感謝你讓我的一天! –

2

這是在你的其他聲明。 Rownum是NUMBER,而Fizz,Buzz和FizzBu​​zz是CHAR。

0
select 
Case when Remainder (rownum,3)=0 then 'Fizz' 
    when Remainder (rownum,5)=0 then 'Buzz' 
    when (remainder (rownum,3)=0 and remainder(ROWNUM,5) = 0) then 'FizzBuzz' 
    else ''||rownum end 
from DUAL 
Connect by level <=100; 

select 
Case when Remainder (rownum,3)=0 then 'Fizz' 
    when Remainder (rownum,5)=0 then 'Buzz' 
    when (remainder (rownum,3)=0 and remainder(ROWNUM,5) = 0) then 'FizzBuzz' 
    else to_char(rownum) end 
from DUAL 
Connect by level <=100; 
+0

由於缺少大小寫表達式分支的錯誤順序,請勿信用(請參閱MT0的解釋答案)。 – mathguy

+1

@mathguy有點苛刻,因爲這確實回答了問題的主要焦點'ORA-00932'異常的問題。 – MT0