반응형
postgresql의 IF-THEN-ELSE 문
다음을 수행하기 위해 postgresql 쿼리를 작성하려고합니다.
if(field1 > 0, field2 / field1 , 0)
이 쿼리를 시도했지만 작동하지 않습니다.
if (field1 > 0)
then return field2 / field1 as field3
else return 0 as field3
감사합니다
여기 PostgreSQL 문서에 명시된 바와 같이 :
SQL CASE 표현식은 다른 프로그래밍 언어의 if / else 문과 유사한 일반 조건식입니다.
귀하의 질문에 구체적으로 대답하는 코드 스 니펫 :
SELECT field1, field2,
CASE
WHEN field1>0 THEN field2/field1
ELSE 0
END
AS field3
FROM test
case when field1>0 then field2/field1 else 0 end as field3
일반적으로 대안 case when ...
은 coalesce(nullif(x,bad_value),y)
(OP의 경우 사용할 수 없음)입니다. 예를 들면
select coalesce(nullif(y,''),x), coalesce(nullif(x,''),y), *
from ( (select 'abc' as x, '' as y)
union all (select 'def' as x, 'ghi' as y)
union all (select '' as x, 'jkl' as y)
union all (select null as x, 'mno' as y)
union all (select 'pqr' as x, null as y)
) q
제공합니다 :
coalesce | coalesce | x | y
----------+----------+-----+-----
abc | abc | abc |
ghi | def | def | ghi
jkl | jkl | | jkl
mno | mno | | mno
pqr | pqr | pqr |
(5 rows)
참고 URL : https://stackoverflow.com/questions/19029842/if-then-else-statements-in-postgresql
반응형
'Program Tip' 카테고리의 다른 글
MySQL의 "IF EXISTS"사용 (0) | 2020.11.20 |
---|---|
IntelliJ에서 한 줄에 대한 경고 비활성화 (0) | 2020.11.20 |
.gitignore 특정 파일 제외 (0) | 2020.11.20 |
오류없이 "conda install --yes --file requirements.txt"를 사용하여 사용 가능한 패키지 만 설치 (0) | 2020.11.20 |
스타-스키마 디자인 (0) | 2020.11.20 |