如何使用mysql计算选择查询中的两列值?
这是我的SQL查询
print(pd.DataFrame([[-4, 7], [-5, 6]],columns=['c','d']))
c d
0 -4 7
1 -5 6
print(df.groupby(['a','b'])\
.apply(lambda x: pd.DataFrame(x['c'].tolist()[0], columns=['c','d'])))
c d
a b
7 5 0 -4 7
1 -5 6
13 5 0 -9 4
1 -3 7
在上面的查询中,我需要计算vatamt和exclvat的总和作为总金额并将其显示。有人可以帮我吗?
答案 0 :(得分:1)
您不能在SELECT
子句中再次重用别名的Calculated表达式。它们只能在GROUP BY
,ORDER BY
,HAVING
子句中重复使用。您将需要再次指定计算表达式,以计算total_amount
:
SELECT cusName,
remarks,
invoiceNo,
invoiceDate,
total_VAT,
bill_tot,
ROUND((bill_tot - total_VAT) * 5/100,2) as vatamt, -- got rid of extra parentheses
ROUND(bill_tot - total_VAT, 2) as exclvat,
ROUND((bill_tot - total_VAT) * 5/100,2) +
ROUND(bill_tot - total_VAT, 2) as total_amount
FROM invoices
where invoiceDate between '2018-11-13' and '2018-11-13'
order by invoiceID;
答案 1 :(得分:0)
如果您想对性能进行可读性排名(尽管对性能的影响可以忽略不计),则还可以使用包装查询:
SELECT cusName,
remarks,
invoiceNo,
invoiceDate,
total_VAT,
bill_tot,
vatamt,
exclvat,
vatampt + exclvat as total_amount
FROM (
SELECT *,
ROUND(((bill_tot - total_VAT) * 5/100),2) as vatamt,
ROUND(bill_tot - total_VAT, 2) as exclvat
FROM invoices
WHERE invoiceDate between '2018-11-13' and '2018-11-13'
ORDER BY invoiceID
) a;
答案 2 :(得分:0)
@Madhur给出的答案可能是效果最好的。但是在MySQL 8中,我们可以利用CTE来避免在select子句中重复常见的逻辑:
WITH cte AS (
SELECT *,
ROUND(((bill_tot - total_VAT) * 5/100),2) AS vatamt,
ROUND(bill_tot - total_VAT, 2) AS exclvat
FROM invoices
WHERE invoiceDate = '2018-11-13'
)
SELECT
cusName,
remarks,
invoiceNo,
invoiceDate,
total_VAT,
bill_tot,
vatamt,
exclvat,
vatamt + exclvat AS total
FROM cte
ORDER BY
invoiceID;