SQL计算查询

时间:2017-02-18 07:31:15

标签: mysql subquery views

SELECT
    (SELECT sum(cost) from cost_table) AS "amount_paid"
FROM member_management;

我需要使用子查询计算的值 下一栏进一步计算。示例如下:

SELECT
    (SELECT sum(cost) from cost_table) AS "amount_paid",
    amount_paid/5 AS "share price"
FROM member_management;

4 个答案:

答案 0 :(得分:0)

您无法在定义它的同一select子句中重用别名。解决这个问题的一种方法是进行计算

SELECT m.*, amount_paid, share_price 
FROM member_management m
cross join 
(
    SELECT sum(cost) as amount_paid, sum(cost) / 5 as share_price 
    from cost_table
) tmp

答案 1 :(得分:0)

由于您无法在选择列表中的另一个表达式中引用列别名,因此需要

  • 在第二次计算
  • 中重复滑动表达式
  • 或者您需要将子查询从选择列表移动到from子句

第二个建议的示例代码:

SELECT
    amount_paid",
    amount_paid/5 AS share price
FROM (SELECT sum(cost) as amount_paid from cost_table) t
Join member_management

答案 2 :(得分:0)

总和(成本)=" amount_paid"和amount_paid / 5 ="股价"然后你应该使用总和(成本)/ 5 ="股价"这样......就这个

SELECT
(SELECT sum(cost) from cost_table) AS "amount_paid",
(SELECT sum(cost)/5 from cost_table) AS "share price"
FROM member_management;

答案 3 :(得分:0)

以上使用的查询仅用于理解概念

“file 1”包含我正在使用的实际查询,“file 2”包含解决方案

[link] https://gist.github.com/anonymous/b497f6a379d26532144ac13bd5fde20e