Error: invalid input syntax for integer: “”

為{幸葍}努か 提交于 2021-02-18 11:12:07

问题


I have this table tbl_buku:

id_buku  judul_buku   tahun_buku
1          Bioogi          2010
2          Fisika          2010
3          Informatika     2012
4          Kimia           2012

I use query like this, but I am getting an error:

select case when t1.tahun_buku=t2.tahun_buku then ''
            else t1.tahun_buku end tahun_buku,t1.judul_buku
from tbl_buku t1 left join tbl_buku t2
on t1.id_buku-1=t2.id_buku;

I want to show table like this:

tahun_buku     judul_buku
2010             Biologi
                 Fisika
2012             Informatika
                 Kimia

How to achieve this?


回答1:


I think the problem in your query is that tahun_buku is of datatype int and you are trying to select an empty string ('').

You have to workarounds:

Change tahun_buku to be varchar (2010,2012..will be consider as strings I dont know if it is ok)

Set:

select case when t1.tahun_buku=t2.tahun_buku then null else t1.tahun_buku end tahun_buku,t1.judul_buku
from tbl_buku t1 left join tbl_buku t2
on t1.id_buku-1=t2.id_buku;



回答2:


  • Use the window function lag() to get values from the previous row.

  • Use NULL for "empty" values in a numeric column - like @apomene already suggested.
    The empty string '' can only be used in character types like text or varchar.

  • Use NULLIF() in this particular case to substitute the NULL value.

SELECT NULLIF(lag(tahun_buku) OVER (ORDER BY tahun_buku, judul_buku)
            , tahun_buku) AS tahun_buku
     , judul_buku
FROM   tbl_buku
ORDER  BY tahun_buku, judul_buku;


来源:https://stackoverflow.com/questions/23911844/error-invalid-input-syntax-for-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!