MySQL-ALIAS的总和未按预期工作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL-ALIAS的总和未按预期工作相关的知识,希望对你有一定的参考价值。
[我是SQL的新手,我试图找到一种方法来添加2个简单列:(,一个累加(col1+col2+col3+col4)
,另一个累加(col5+col6+col7+col8)
。
问题是,我已经尝试过:(col1+col2+col3+col4) as total
,(sum(col1)+sum(col2)+sum(col3)+sum(col4)) as total
。
但是所有行的输出均为“ 0”,它们没有对值求和。
任何提示?
感谢进阶!
下面是我的查询:
SELECT CONCAT(extract(day from datetime_req),"_",extract(month from datetime_req),"_",
extract(year from datetime_req),"_",`card_acceptor_id_code`,"_",`terminal_id`,"_",`ext_nserie_simcard`,"_",`ext_connection_type`) AS 'col0',
COUNT(CASE WHEN `rsp_code_rsp` = '00' AND `tran_reversed` = '0' THEN 'APROVADA EFETIVADA' END) AS 'Col1',
COUNT(CASE WHEN `rsp_code_rsp` != '00' AND `tran_reversed` = '0' THEN 'NEGADA EFETIVADA' END) AS 'Col2',
COUNT(CASE WHEN `rsp_code_rsp` = '00' AND `tran_reversed` != '0' THEN 'APROVADA DESFEITA' END) AS 'Col3',
COUNT(CASE WHEN `rsp_code_rsp` != '00' AND `tran_reversed` != '0' THEN 'NEGADA DESFEITA' END) AS 'Col4',
SUM(CASE WHEN `rsp_code_rsp` = '00' AND `tran_reversed` = '0' THEN `tran_amount_req` ELSE 0 END)/100 AS 'col5',
SUM(CASE WHEN `rsp_code_rsp` != '00' AND `tran_reversed` = '0' THEN `tran_amount_req` ELSE 0 END)/100 AS 'col6',
SUM(CASE WHEN `rsp_code_rsp` = '00' AND `tran_reversed` != '0' THEN `tran_amount_req` ELSE 0 END)/100 AS 'Col7',
SUM(CASE WHEN `rsp_code_rsp` != '00' AND `tran_reversed` != '0' THEN `tran_amount_req` ELSE 0 END)/100 AS 'Col8'
FROM `table`
WHERE `datetime_req` BETWEEN '2019-10-29 00:00:00' AND '2019-10-29 23:59:59'
GROUP BY 1
答案
您不能在同一SELECT
列表中引用别名,也不能嵌套聚合功能。您需要将查询放入子查询中。
SELECT col0, SUM(col1+col2+col3+col4) AS total1, SUM(col5, col6, col7, col8) AS total2
FROM (
SELECT CONCAT(extract(day from datetime_req),"_",extract(month from datetime_req),"_",
extract(year from datetime_req),"_",`card_acceptor_id_code`,"_",`terminal_id`,"_",`ext_nserie_simcard`,"_",`ext_connection_type`) AS 'col0',
COUNT(CASE WHEN `rsp_code_rsp` = '00' AND `tran_reversed` = '0' THEN 'APROVADA EFETIVADA' END) AS 'Col1',
COUNT(CASE WHEN `rsp_code_rsp` != '00' AND `tran_reversed` = '0' THEN 'NEGADA EFETIVADA' END) AS 'Col2',
COUNT(CASE WHEN `rsp_code_rsp` = '00' AND `tran_reversed` != '0' THEN 'APROVADA DESFEITA' END) AS 'Col3',
COUNT(CASE WHEN `rsp_code_rsp` != '00' AND `tran_reversed` != '0' THEN 'NEGADA DESFEITA' END) AS 'Col4',
SUM(CASE WHEN `rsp_code_rsp` = '00' AND `tran_reversed` = '0' THEN `tran_amount_req` ELSE 0 END)/100 AS 'col5',
SUM(CASE WHEN `rsp_code_rsp` != '00' AND `tran_reversed` = '0' THEN `tran_amount_req` ELSE 0 END)/100 AS 'col6',
SUM(CASE WHEN `rsp_code_rsp` = '00' AND `tran_reversed` != '0' THEN `tran_amount_req` ELSE 0 END)/100 AS 'Col7',
SUM(CASE WHEN `rsp_code_rsp` != '00' AND `tran_reversed` != '0' THEN `tran_amount_req` ELSE 0 END)/100 AS 'Col8'
FROM `table`
WHERE `datetime_req` BETWEEN '2019-10-29 00:00:00' AND '2019-10-29 23:59:59'
GROUP BY col0
) AS x
GROUP BY col0
以上是关于MySQL-ALIAS的总和未按预期工作的主要内容,如果未能解决你的问题,请参考以下文章