简体   繁体   中英

MySQL union and sum two table

I need a solution for display same day records and show SUM of each column, so far I have a query to show union records like:

SELECT 
    datetime, 
    remarks, 
    void, 
    invoice, 
    reload, 
    redeem 
FROM
    (
      SELECT datetime, remarks, '' void, '' invoice, points_intake reload, '' redeem, 1 ord
      FROM bpp_intake_logs
      WHERE outlet = 'KUL' AND DATE(datetime) = '2017-06-13'
      UNION ALL

      SELECT datetime, remarks, void, invoice, '', points_consume, 2
      FROM bpp_consume_logs
      WHERE outlet = 'KUL' AND DATE(datetime) = '2017-06-13' 
    ) q
ORDER BY datetime DESC, ord 

and the result table is show like:

datetime            | remarks                        | void | invoice  | reload | redeem |
2017-06-13 15:53:31 | Point restored - void XY203460 |      |          | 10     |        |
2017-06-13 15:37:27 | reload / top-up credit         |      |          | 10     |        |
2017-06-13 15:35:56 | redeem from VIP card           |  1   | XY203460 |        | 10     |
2017-06-13 15:16:03 | redeem from VIP card           |      | XY203456 |        | 5      |

Now, I wanted to add a cell to sum each reload and redeem at the bottom of its belonging column, like:

datetime            | remarks                        | void | invoice  | reload | redeem |
2017-06-13 15:53:31 | Point restored - void XY203460 |      |          | 10     |        |
2017-06-13 15:37:27 | reload / top-up credit         |      |          | 10     |        |
2017-06-13 15:35:56 | redeem from VIP card           |  1   | XY203460 |        | 10     |
2017-06-13 15:16:03 | redeem from VIP card           |      | XY203456 |        | 5      |
                                                                       | 20     | 15     |

As seen, SUM 20 and 15 are allocated at the bottom cell.

Is that possible to get a results in this way?

Perhaps this is what youre looking for????

SELECT 
datetime, 
remarks, 
void, 
invoice, 
SUM(reload), 
SUM(redeem) 
FROM
(
  SELECT datetime, remarks, '' void, '' invoice, points_intake reload, '' redeem, 1 ord
  FROM bpp_intake_logs
  WHERE outlet = 'KUL' AND DATE(datetime) = '2017-06-13'
  UNION ALL

  SELECT datetime, remarks, void, invoice, '', points_consume, 2
  FROM bpp_consume_logs
  WHERE outlet = 'KUL' AND DATE(datetime) = '2017-06-13' 
) q
GROUP BY datetime desc, remarks asc, void asc, invoice asc with rollup

ORDER BY datetime DESC, ord 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM