I have a table "records" [Records][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
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.
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:
SELECT
typeofservice,
Coalesce(SUM(incomecost), 0) AS incomecost,
Coalesce(SUM(expensecost), 0) AS expensecost
FROM records
GROUP BY typeofservice
WITH ROLLUP
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.