해당 월 조회시 당월 데이터가 없어도 0으로 표시하는 방법 문의 0 2 379

by 릿췌 [Tibero] [2020.03.31 09:45:31]


안녕하세요 문의드립니다

예를들어 3월데이터 조회시 1월 2월데이터는 조회되는데 3월 데이터가 없다면 3월에 대한 행이 생기지 않고

                                                                                         데이터가 있다면 3월 행과 데이터 가 생깁니다 

 

저는 데이터가 없어도 행이 생기고 0으로 표시하게 바꾸고싶은데요

 

어떤방법이 있는지 알려주시면 감사 하겠습니다

by 마농 [2020.03.31 10:24:23]

어떻게 조회하는지에 따라 대응 방법이 달라질 수 있습니다.
사용 쿼리를 보여주세요.


by 엔젤 [2020.04.01 15:17:41]

2020년만 조회, 1/2/4/5/7 월에는 값이 들어 있다는 가정하에서 생각해보았습니다.

더 효율적인 방법은 다른분이 올려주실거라 믿으며..

create table test_val (target_year integer, target_month integer, target_val integer);
insert into test_val values (2020, 1, 1000);
insert into test_val values (2020, 2, 2000);
insert into test_val values (2020, 4, 4000);
insert into test_val values (2020, 5, 5000);
insert into test_val values (2020, 7, 7000);
select * from test_val;

with a as (
 select 2020 as target_year, 1 as target_month, 0 as target_val
 union
 select 2020 as target_year, 2 as target_month, 0 as target_val
 union
 select 2020 as target_year, 3 as target_month, 0 as target_val
 union
 select 2020 as target_year, 4 as target_month, 0 as target_val
 union
 select 2020 as target_year, 5 as target_month, 0 as target_val
 union
 select 2020 as target_year, 6 as target_month, 0 as target_val
 union
 select 2020 as target_year, 7 as target_month, 0 as target_val
 union
 select 2020 as target_year, 8 as target_month, 0 as target_val
 union
 select 2020 as target_year, 9 as target_month, 0 as target_val
 union
 select 2020 as target_year, 10 as target_month, 0 as target_val
 union
 select 2020 as target_year, 11 as target_month, 0 as target_val
 union
 select 2020 as target_year, 12 as target_month, 0 as target_val
), b as (
 select test_val.*
 from test_val, a
 where test_val.target_month = a.target_month
), c as (
 select * 
 from a
 where NOT EXISTS (select * from b where a.target_month = b.target_month)
)
select target_year, target_month, target_val
from
(
select * from b
union
select * from c
) as t
order by target_month

 

댓글등록
SQL문을 포맷에 맞게(깔끔하게) 등록하려면 code() 버튼을 클릭하여 작성 하시면 됩니다.
로그인 사용자만 댓글을 작성 할 수 있습니다. 로그인, 회원가입