tags:

views:

50

answers:

1

Using MySQL 5 with table "abrechnung"

id   datum     title   betrag  wal jon  al  ben
7   2010-02-08  Essen   1362     0   0   1   0
8   2010-02-15  Essen   324      0   0   1   2
9   2010-02-15  Essen   5732     0   0   1   2
10  2010-02-15  Essen   3245     0   2   1   2 

What I want in the end is: Each rows "betrag" is divided through a number and then added to the final result. The number that is divided through is 4 - the amount of 2 in the current row.

My current approach is as follows:

SELECT SUM(betrag) AS "W->A" FROM abrechnung WHERE (wal = "0" and al = "1");

This basically selects the entrys that I want to have added to the final result. Result in this case: 10663.

Actually the final result shall be:

  1362 / 4 (no number 2 in that row for wal, jon, al or ben)
+  324 / 3 (there is one 2 in that row for ben)
+ 5732 / 3 (same)
+ 3245 / 2 (there are 2 2's in that row)
-----------
  3 981.66

I hope this is clear to understand.

Thank you.

+1  A: 
SELECT SUM(betrag / (
 4-CASE WHEN wal = 2 THEN 1 ELSE 0 END
  -CASE WHEN jon = 2 THEN 1 ELSE 0 END
  -CASE WHEN al  = 2 THEN 1 ELSE 0 END
  -CASE WHEN ben = 2 THEN 1 ELSE 0 END
))
AS "W->A" FROM abrechnung 
DVK
This is Sybase syntax, I don't have MySQL access now to test if it works there as well but it ought to
DVK
thank you, but this does not cover if there are 2 2's in a row
Acron
I think it does, since it is making a substraction per every 2..its 4-(if wal=2 then 1 else 0)-(if jon=2 then 1 else 0)-usw...
jpabluz
love you DVK ;)
Acron