我有一张表格如下:
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
我想要一个SQL查询,它会给我一个数字,它给出了所有记录的总和,数量乘以价格,只有当'gift'字段时才将giftprice添加到乘法前的价格中设置为1。
伪代码
foreach(record){
if(gift == 1){ linetotal = (price + giftprice) * quantity; }
else { linetotal = price * quantity; }
total = total + linetotal;
}
答案 0 :(得分:9)
你可以这样做:
SELECT product, (price + gift * giftprice) * quantity AS total
FROM theTable
由于gift = 0
答案 1 :(得分:3)
SELECT SUM( (price + giftprice*gift) * quantity)
AS total
FROM yourTable
;