是否可以使用两列的值来计算新列?
查询:
SELECT department.id AS 'ID',
department.des AS 'Department',
CASE department.des
WHEN 'Retail Sales' THEN ( IFNULL(SUM(form.amount), 0)
+ (SELECT SUM(creditnote.amount)
FROM wf_creditnote AS creditnote
WHERE creditnote.status = 'a'
AND YEAR(creditnote.submittime) = 2013
AND MONTH(creditnote.submittime) = 11) )
ELSE IFNULL(SUM(form.amount), 0)
END AS 'Actual',
budget.budget AS 'Budget'
FROM (wf_analysis_billcodes AS billcode
LEFT JOIN wf_waiving AS form
ON form.billcode = billcode.bill_code
AND form.status = 'a'
AND YEAR(form.sbmt) = 2013
AND MONTH(form.sbmt) = 11),
wf_analysis AS department,
wf_analysis_budgets AS budget
WHERE department.id = billcode.dept_id
AND department.id = budget.dept_id
AND budget.year = 2013
AND budget.month = 11
GROUP BY department.des
ORDER BY department.id ASC
结果:
+----+------------+--------+--------+ | ID | Department | Actual | Budget | +----+------------+--------+--------+ | 1 | IT | 327 | 200 | | 2 | Finance | 312 | 500 | | 3 | Marketing | 100 | 650 | | 4 | HR | 423 | 320 | +----+------------+--------+--------+
我想通过SELECT
声明添加一个百分比列。
答案 0 :(得分:2)
将查询转换为子查询,并以这种方式在主查询中执行计算:
SELECT q.*,
((Budget-Actual)*100/Budget) AS Percent
FROM (
... your query ...
) AS q
演示 - > http://www.sqlfiddle.com/#!2/9b061/2
为了避免除以0错误,可以使用案例表达式:
SELECT q.*,
CASE WHEN Bydget <> 0
THEN ((Budget-Actual)*100/Budget)
ELSE 0
END AS Percent
FROM (
... your query ...
) AS q