我正在开发一个带有MySQL数据库的PHP应用程序,该数据库存储了公司所做的交易清单。
这些销售和购买都保存在同一个表格中,标识符列中包含p或s。
我希望通过将salesOrPurchase ='s'的所有交易全部加起来计算利润,然后对salesOrPurchase ='p'进行相同的操作,然后从我们的销售中扣除我们的购买以计算出利润。
有些事情:
SELECT
SUM(amount) WHERE salesOrPurchase = 's' as SalesTotal,
SUM(amount) WHERE salesOrPurchase = 'p' as PurchasesTotal,
(SalesTotal - PurchasesTotal) as Profit
FROM transactions
答案 0 :(得分:1)
子查询怎么样?
SELECT SalesTotal, PurchasesTotal, (SalesTotal-PurchasesTotal) as Profit
FROM (SELECT (SELECT SUM(amount) FROM transactions WHERE salesOrPurchase = 's') as SalesTotal,
(SELECT SUM(amount) FROM transactions WHERE salesOrPurchase = 'p') as PurchasesTotal
) t
答案 1 :(得分:0)
您不能在定义它们的同一select
中使用别名。相反,对所有三个使用条件聚合:
SELECT SUM(case when salesOrPurchase = 's' then amount end) as SalesTotal,
SUM(case when salesOrPurchase = 'p' then amount end) as PurchasesTotal,
SUM(case when salesOrPurchase = 's' then amount
when salesOrPurchase = 'p' then - amount
end) as Profit
FROM transactions;