我有一张表如下:
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
Run Code Online (Sandbox Code Playgroud)
我希望有一个SQL查询,它会给我一个数字,给我一个数量乘以价格的所有记录的总和,只有当'gift'字段设置为'时,才将giftprice添加到乘法前的价格中1.
伪代码
foreach(record){
if(gift == 1){ linetotal = (price + giftprice) * quantity; }
else { linetotal = price * quantity; }
total = total + linetotal;
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
SELECT product, (price + gift * giftprice) * quantity AS total
FROM theTable
Run Code Online (Sandbox Code Playgroud)
因为如果没有任何补充gift = 0
.