sql문 쿼리 질문하고 싶습니다. 0 2 737

by 라인란 [SQL Query] [2021.01.03 18:49:53]


 

db 값입니다.

id store_id purchase_type price
1 1 신용카드 1000
2 1 신용카드 500
3 1 무료 1000
4 1 무료 10000
5 1 쿠폰 500

 

이게 view화면에 뿌려질 결과값입니다.

매장 신용카드별 합계 현금 결제 별 합계 무료 결제 별 합계 쿠폰별 합계
1 1500 11000 0 500
         

 

제가 원하는 결과는 매장별로   sum(purchase_type="신용카드") as 1

sum(purchase_type="무료") as 2,  sum(purchase_type="쿠폰") as 3 이런 방법으로 if문이나 case 문을 mysql로 하고 싶은데 어떻게 해야 할지 모르곘습니다.

by pajama [2021.01.04 00:07:54]

샘플 데이터의 무료를 현금으로 바꿨습니다~

 

with t as (
select 1 id, 1 store_id, '신용카드' purchase_type, 1000 price union all
select 2 id, 1 store_id, '신용카드' purchase_type, 500 price union all
select 3 id, 1 store_id, '현금' purchase_type, 1000 price union all
select 4 id, 1 store_id, '현금' purchase_type, 10000 price union all
select 5 id, 1 store_id, '쿠폰' purchase_type, 500 price
)
select store_id 매장,
       sum(case when purchase_type ='신용카드' then price else 0 end) 신용카드별_합계,
       sum(case when purchase_type ='현금' then price else 0 end) 현금결제별_합계,
       sum(case when purchase_type ='무료' then price else 0 end) 무료결제별_합계,
       sum(case when purchase_type ='쿠폰' then price else 0 end) 쿠폰별_합계
 from t
group by store_id

 


by 라인란 [2021.01.04 12:15:52]

pajama님이 올려주신 답변을 토대로  작성하였더니 해결됐습니다.. 감사합니다.

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