我有通过联合加入的查询,它在行中分别为我提供了理想的结果,我想将这两行加入并添加其值,但是我不知道如何执行查询
SELECT
`b`.`main_code`,
`b`.`account_title`,
SUM(CASE
WHEN
`a`.`type` = 'CP'
AND `a`.`interactive_person` = '6'
AND `a`.`date` BETWEEN '2018-02-12' AND '2018-07-31'
THEN
`a`.`balance`
ELSE 0
END) AS `credit`,
SUM(CASE
WHEN
`a`.`type` = 'CR'
AND `a`.`interactive_person` = '6'
AND `a`.`date` BETWEEN '2018-02-12' AND '2018-07-31'
THEN
`a`.`balance`
ELSE 0
END) AS `debit`,
SUM(CASE
WHEN
`a`.`type` = 'CR'
AND `a`.`interactive_person` = '6'
AND `a`.`date` BETWEEN '2018-02-12' AND '2018-07-31'
THEN
`a`.`balance`
WHEN `a`.`type` = 'CP' THEN - 1 * `a`.`balance`
ELSE 0
END) AS `balance`
FROM
`vouchers` AS `a`,
`data` AS `b`
WHERE
`a`.`interactive_person` = '6'
AND `a`.`post_status` = 'yes'
AND `a`.`interactive_person` = `b`.`main_code`
AND `a`.`date` BETWEEN '2018-02-12' AND '2018-07-31'
UNION SELECT
`b`.`main_code`,
`b`.`account_title`,
IFNULL(SUM(`a`.`debit`), 0) AS `debit`,
IFNULL(SUM(`a`.`credit`), 0) AS `credit`,
(`debit` - `credit`) AS `balance`
FROM
`journal_vouchers` AS `a`,
`data` AS `b`
WHERE
`a`.`account_id` = '44'
AND `a`.`date` BETWEEN '2018-02-12' AND '2018-07-31'
AND `post_status` = 'yes'
AND `cancel_status` = 'off'
AND `a`.`account_id` = `b`.`account_code`
GROUP BY `b`.`main_code`;
查询有点复杂,让我解释一下:
该查询从3个表中获取结果,但主要的是,在并集之前,它从两个表中获取结果,在并集两个表之后,其中一个表data
与两个表进行交互。简而言之,我得到的结果是
+-----------+---------------+--------+-------+---------+
| main_code | account_title | credit | debit | balance |
+-----------+---------------+--------+-------+---------+
| 6 | cash account | 5200 | 520 | -4680 |
+-----------+---------------+--------+-------+---------+
| 6 | cash account | 0 | 200 | -200 |
+-----------+---------------+--------+-------+---------+
我想要按主代码分组的完整查询,但我不知道该怎么做 我希望结果是
6 | cash account | 5200 | 320 | -4880