计算SQL百分比

时间:2014-02-07 13:23:17

标签: sql

我有一个包含产品的数据库,客户需要输入折扣百分比。 折扣必须在数据库中计算,以便查询返回所有价格 - 折扣

我该怎么做?

SELECT product.name sizes.height, sizes.width, product_sizes.price 
FROM   product_sizes as s 
JOIN   sizes ON s.sizeid = sizes.sizeid, product 
JOIN   product_sizes on product.productid = product_sizes.productid 
WHERE  product.productid=1

由于

2 个答案:

答案 0 :(得分:1)

首先我会像你这样做你的查询

SELECT p.name, s.height, s.width, ps.price 
FROM   product_sizes as ps, product as p, sizes as s 
WHERE  ps.sizeid = s.sizeid 
AND    p.productid = ps.productid
AND    p.productid=1

比你必须在选择中计算它 尝试一些像,它未经测试,我真的不知道这是否有效,但它应该...

SELECT p.name, s.height, s.width, (((ps.price/100)*x)+ps.price) as newPrice
FROM   product_sizes as ps, product as p, sizes as s 
WHERE  ps.sizeid = s.sizeid 
AND    p.productid = ps.productid
AND    p.productid=1

当然你必须在那里放一些X是:)

这行是什么??? ....(你的来源)

SELECT product.name sizes.height, sizes.width, product_sizes.price 
-------------------^ there is a comma missing
FROM   product_sizes as s 
JOIN   sizes ON s.sizeid = sizes.sizeid, product 
--------------------------------------------^ what is this ?
JOIN   product_sizes on product.productid = product_sizes.productid 
WHERE  product.productid=1

答案 1 :(得分:0)

通常,您可以在查询中应用数学运算符,例如乘法和减法,假设数据是数字。从您的问题的声音来看,您似乎并不知道这一点,所以这是您可以做的事情的简化示例:

CREATE TABLE Discount(
  Price DECIMAL(10,2)
)

INSERT INTO Discount
VALUES (23.4)
  , (20.9)
  , (16.8)

SELECT Price
  -- We're multiplying the price column by a discount percent of 10%
  , (Price * .10) Discount
  -- We're subtracting that discount amount from the price
  , Price - (Price * .10) PriceIncludingDiscount
FROM Discount

SQL Fiddle demonstration

在您的情况下,您的列product_sizes.price将乘以折扣并从价格中扣除,如果您想要包含折扣金额,或者只是乘以折扣百分比,如果折扣只是您的折扣寻求(在问题中有点不清楚)。