[英]Get total value of the same column multiple rows and total of two different rows (mysql query)
I have a table "records" [Records][1] 我有一张表“记录”[记录] [1]
select typeofservice,
Coalesce(sum(incomecost,expensecost),0) 'incomecost,expensecost'
from records
where dateoftrans = '2016-11-22'
group by typeofservice with rollup;
I want to be able to have the result on the second image and this is my query... and all of this transactions happened on one day. 我希望能够在第二张图像上得到结果,这是我的查询......所有这些交易都发生在一天。 Please help
请帮忙
https://i.stack.imgur.com/fLYav.png https://i.stack.imgur.com/fLYav.png
The following query assumes that, for a given type of service, you want to report an income when the sum of the income cost exceeds the sum of the expense cost, and vice-versa. 以下查询假定,对于给定类型的服务,您希望在收入成本总和超过费用成本之和时报告收入,反之亦然。 In each case, the difference between income and expense is reported in the appropriate column, with
NULL
being reported in the alternate column. 在每种情况下,收入和费用之间的差异在适当的列中报告,在备用列中报告
NULL
。
SELECT typeofservice,
CASE WHEN SUM(incomecost) - SUM(expensecost) > 0
THEN SUM(incomecost) - SUM(expensecost)
ELSE NULL END AS incomecost,
CASE WHEN SUM(expensecost) - SUM(incomecost) > 0
THEN SUM(expensecost) - SUM(incomecost)
ELSE NULL END AS expensecost
FROM records
WHERE dateoftrans = '2016-11-22'
GROUP BY typeofservice
WITH ROLLUP
If only for second image's result, you can try sum(incomecost)
and sum(expensecost)
like this: 如果仅针对第二张图像的结果,您可以尝试
sum(incomecost)
和sum(expensecost)
如下所示:
SELECT
typeofservice,
Coalesce(SUM(incomecost), 0) AS incomecost,
Coalesce(SUM(expensecost), 0) AS expensecost
FROM records
GROUP BY typeofservice
WITH ROLLUP
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.