Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query Count on Column Information

Tags:

sql

count

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.

like image 200
Acron Avatar asked Apr 29 '26 12:04

Acron


1 Answers

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 
like image 200
DVK Avatar answered May 01 '26 02:05

DVK