I'm trying to use defined variables to calculate a column but the result does not add up correctly. I've tried moving the variable declaration inside the brackets or playing around with the aggregation but the calculated column (Profit in the example below) does not match the result of just writing out the full calculation.
Please have a look at example query below. Query contains a full join so I included it since it might be relevant?
select
a.ID,
c.Group1,
a.group2,
b.group3,
@turnover :=
sum(
a.Qty *
a.Price *
(100 - a.discount) / 100 *
a.Rate
) as Turnover,
@cost :=
sum(
a.Qty *
a.Cost
) as Cost,
@turnover - @cost as Profit
from
a,
b,
c
where
a.id=b.id and
a.id2=c.id
group by
a.ID,
c.Group1,
a.group2,
b.group3
Expected outcome:
╔════╦════════╦═════════╦═════════╦══════════╦═══════╦════════╗
║ ID ║ Group1 ║ Group 2 ║ Group 3 ║ Turnover ║ Cost ║ Profit ║
╠════╬════════╬═════════╬═════════╬══════════╬═══════╬════════╣
║ 1 ║ A ║ X ║ E ║ 2.13 ║ 1.25 ║ 0.89 ║
║ 2 ║ A ║ Y ║ F ║ 1.93 ║ 1.61 ║ 0.32 ║
║ 2 ║ A ║ X ║ G ║ 46.74 ║ 36.93 ║ 9.81 ║
╚════╩════════╩═════════╩═════════╩══════════╩═══════╩════════╝
Actual outcome:
╔════╦════════╦═════════╦═════════╦══════════╦═══════╦════════╗
║ ID ║ Group1 ║ Group 2 ║ Group 3 ║ Turnover ║ Cost ║ Profit ║
╠════╬════════╬═════════╬═════════╬══════════╬═══════╬════════╣
║ 1 ║ A ║ X ║ E ║ 2.13 ║ 1.25 ║ 9.81 ║
║ 2 ║ A ║ Y ║ F ║ 1.93 ║ 1.61 ║ 9.81 ║
║ 2 ║ A ║ X ║ G ║ 46.74 ║ 36.93 ║ 9.81 ║
╚════╩════════╩═════════╩═════════╩══════════╩═══════╩════════╝
Sample of the (joined) data in relation to the expected outcome.
╔════╦═════════╦═════════╦═════════╦═════╦═══════╦══════════╦══════╦═══════╗
║ ID ║ Group 1 ║ Group 2 ║ Group 3 ║ Qty ║ Price ║ Discount ║ Rate ║ Cost ║
╠════╬═════════╬═════════╬═════════╬═════╬═══════╬══════════╬══════╬═══════╣
║ 1 ║ A ║ X ║ E ║ 2 ║ 1.065 ║ 0 ║ 1 ║ 0.625 ║
║ 2 ║ A ║ Y ║ F ║ 5 ║ 0.193 ║ 0 ║ 1 ║ 0.161 ║
║ 2 ║ A ║ Y ║ F ║ 5 ║ 0.193 ║ 0 ║ 1 ║ 0.161 ║
║ 2 ║ A ║ X ║ G ║ 1 ║ 20.74 ║ 0 ║ 1 ║ 20.93 ║
║ 2 ║ A ║ X ║ G ║ 1 ║ 13 ║ 0 ║ 2 ║ 16 ║
╚════╩═════════╩═════════╩═════════╩═════╩═══════╩══════════╩══════╩═══════╝