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로 하고 싶은데 어떻게 해야 할지 모르곘습니다.
샘플 데이터의 무료를 현금으로 바꿨습니다~
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