union 했는데 결과값이 2개가 나옵니다.
본문
(select SUBSTRING(wr_29,1,7) as od_date, mb_id, count(*) as cnt , sum(wr_23) as tot
from {$write_table_a}
where SUBSTRING(wr_29,1,7) between '2022-01' and '2022-05'
group by od_date)
union
(select SUBSTRING(wr_29,1,7) as od_date, mb_id, count(*) as cnt , sum(wr_23) as tot
from {$write_table_b}
where SUBSTRING(wr_29,1,7) between '2022-01' and '2022-05'
group by od_date)
order by od_date desc
write_table_a와 write_table_b 게시판의 모든 테이블값은 같습니다.
하나씩 했을때는 잘 나옵니다.
해서 2개를 하나로 보여주고 싶은데 결과값이 2개씩 나옵니다.
!-->
답변 2
select od_date, sum( cnt) from ( (select SUBSTRING(wr_29,1,7) as od_date, mb_id, count(*) as cnt , sum(wr_23) as tot
from {$write_table_a}
where SUBSTRING(wr_29,1,7) between '2022-01' and '2022-05'
group by od_date)
union
(select SUBSTRING(wr_29,1,7) as od_date, mb_id, count(*) as cnt , sum(wr_23) as tot
from {$write_table_b}
where SUBSTRING(wr_29,1,7) between '2022-01' and '2022-05'
group by od_date) ) A
group by od_date desc
질문이 조금 이상합니다.
union 은 각각 쿼리 결과에서 중복되는 것을 제거하고 합쳐서 나오게 됩니다.
그래서 2개씩 나오는 이유는, 결과가 다르기 때문입니다.
가령, union 상단의 쿼리에서 2022-04 | 123번 의 결과가 있고,
union 하단의 쿼리에서 2022-04 | 2번 의 결과가 있기 때문에
2022-04 | 123번
2022-04 | 2번
과 같이 나온 것입니다.
union 상단의 쿼리에서 2022-04 | 77번 의 결과가 있고,
union 하단의 쿼리에서 2022-04 | 77번 의 결과가 있다면
2022-04 | 77번 하나만 나오게 됩니다.
'하나씩 했을 때는 잘 나옵니다'와 매치되지 않습니다.
union 상단과 하단의 쿼리를.. 다시한번 실행/검토해보는 것이 좋을 듯 싶습니다. https://blog.bsmind.co.kr/377
답변을 작성하시기 전에 로그인 해주세요.