题目链接:点击打开链接
题目大意:略。
解题思路:先将退单表 union all 到交易表,无非是把 state 标记为一个新的状态,比如 cancel,这样两张表可以合并操作,思路就清晰很多。
第二个案例为什么二月份 CB 会没有?
因为此时此地 approved 和 charge 都没有,所以根据题目要求需要过滤掉。
AC 代码
--解决方案(1) WITHt1AS(SELECT*FROMTransactionsUNIONALLSELECTtrans_id, country, 'cancel'state, amount, c.trans_dateFROMChargebackscJOINTransactionstONc.trans_id=t.id), t2AS(SELECTDATE_FORMAT(trans_date, '%Y-%m') month, country, COUNT(IF(state='approved', 1, null)) approved_count, SUM(IF(state='approved', amount, 0)) approved_amount, COUNT(IF(state='cancel', 1, null)) chargeback_count, SUM(IF(state='cancel', amount, 0)) chargeback_amountFROMt1GROUPBYmonth, country) SELECT*FROMt2WHERE!(approved_count=0ANDchargeback_count=0) --解决方案(2) SELECTmonth, country, COUNT(IF(tag=1, 1, NULL)) ASapproved_count, SUM(IF(tag=1, amount, 0)) ASapproved_amount, COUNT(IF(tag=0, 1, NULL)) ASchargeback_count, SUM(IF(tag=0, amount, 0)) ASchargeback_amountFROM ( SELECTcountry, amount, 1AStag, date_format(trans_date, '%Y-%m') ASmonthFROMTransactionsWHEREstate='approved'UNIONALLSELECTcountry, amount, 0AStag, date_format(c.trans_date, '%Y-%m') ASmonthFROMTransactionsAStRIGHTOUTERJOINChargebacksAScONt.id=c.trans_id) AStempGROUPBYmonth, country;