klox
klox

Reputation: 2093

how to insert some formula in mysql?

i want to calculating one row at table "counter". i try to make my table like:

name          black     yellow     white        qty_job      total
david           1        0          0            2             ?
andrew          0        1          1            4              ?

the formula to calculate is :

total = (nblack * 1) + (nyellow * 1) + (nwhite * 0.4) / qty_job
total = (1 * 1) + (0 * 1) + (0 * 0.4) / 2 = 0.5

how to insert this formula at mysql code? especially at SELECT method.

Upvotes: 4

Views: 18280

Answers (3)

janelle
janelle

Reputation: 11

DECLARE @Number As int, @Number2 As int
SET @Number = 5
WHILE @Number >= 1
BEGIN
PRINT @Number
SET @Number = @Number - 1

PRINT @Number2
SET @Number2 = @Number * (@Number2 - 1)

PRINT 'The Factorial of'
PRINT @Number
PRINT 'is'
PRINT @Number2

END 
GO

Upvotes: 1

Lekensteyn
Lekensteyn

Reputation: 66465

You shouldn't / can't make a row with a certain formula in it. You should use this query to retrieve the total:

SELECT
    name,
    black,
    yellow,
    white,
    qty_job
    (SUM(black) + SUM(yellow) + SUM(white)*0.4) / qty_job AS total
FROM counter
GROUP BY name;

Upvotes: 5

Hendra Jaya
Hendra Jaya

Reputation: 1628

Another alternative is to create a view :

CREATE VIEW test AS
SELECT id, (black * 1) + (yellow * 1) + (white * 0.4) / qty_job as total FROM counter;

The rest should be easy, you could do something like this :

select
 counter.id,
 black,
 yellow,
 white,
 test.total
from
 counter,
 test
where
  counter.id = test.id

Upvotes: 2

Related Questions