开发者

Complex arithmetic in MySQL query

I have a table as follows:

product | quantity | price | gift | giftprice
--------|----------|-------|------|----------
1       | 2        | 9.99  | 0    | 4.99
2       | 3        | 3.50  | 1    | 2.25
3       | 1        | 4.75  | 1    | 1.50

What I'd like to have an SQL query that will give me a figure that gives me the sum of all the records with quantity multiplied by price with the giftpri开发者_JAVA百科ce being added to the price before multiplication only if the 'gift' field is set to 1.

Pseudocode

foreach(record){
   if(gift == 1){ linetotal = (price + giftprice) * quantity; }
   else { linetotal = price * quantity; }
   total = total + linetotal;
}


You can just do:

SELECT product, (price + gift * giftprice) * quantity AS total
FROM theTable

Since nothing will be added if gift = 0.


SELECT SUM( (price + giftprice*gift) * quantity)
       AS total
FROM yourTable
;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜