如何使用mysql查询进行划分

时间:2011-02-14 08:08:02

标签: mysql

这是我的查询

SELECT currency_code, SUM(
CASE
WHEN TYPE = 'buy'
THEN to_amount
END ) AS BUY, SUM(
CASE
WHEN TYPE = 'sell'
THEN to_amount
END ) AS SELL, SUM(
CASE
WHEN TYPE = 'sell'
THEN rate
END ) AS SELL_RATE, SUM(
CASE
WHEN TYPE = 'buy'
THEN rate
END ) AS BUY_RATE
FROM tb_currency
LEFT JOIN tb_bill ON tb_currency.CURRENCY_ID = tb_bill.CURRENCY_ID
AND tb_bill.TYPE
IN (
'buy', 'sell'
)

输出

enter image description here

现在我想将 BUY 字段中的值除以 BUY_RATE 字段中的值。我之前尝试了几个查询并收到错误消息'Unknown column type BUY'。 怎么解决这个问题?

1 个答案:

答案 0 :(得分:1)

你需要做一个subselect,像这样

SELECT *, (BUY/BUY_RATE) AS DIV_VALUE FROM (
    SELECT currency_code, SUM(
    CASE
    WHEN TYPE = 'buy'
    THEN to_amount
    END ) AS BUY, SUM(
    CASE
    WHEN TYPE = 'sell'
    THEN to_amount
    END ) AS SELL, SUM(
    CASE
    WHEN TYPE = 'sell'
    THEN rate
    END ) AS SELL_RATE, SUM(
    CASE
    WHEN TYPE = 'buy'
    THEN rate
    END ) AS BUY_RATE
    FROM tb_currency
    LEFT JOIN tb_bill ON tb_currency.CURRENCY_ID = tb_bill.CURRENCY_ID
    AND tb_bill.TYPE
    IN (
    'buy', 'sell'
    )
)