我有一个名为Orders的表
PurchaseID VARCHAR
purchaseDate DATETIME
purchasePrice FLOAT
我想找到一天购买价格与另一天购买价格之间的差异 - puyrchaseID将是相同的。(这只是一个示例表格)
SELECT a.purchasePrice AS purchasePriceDay1 , b.purchasePrice AS purchasePriceDay1
from Orders a , Orders b
where a.PurchaseID = b.PurchaseID
这实际上是否有用
答案 0 :(得分:3)
SELECT
a.PurchaseID,
ABS(a.PurchaseID - b.PurchaseID) AS diff
FROM
PurchaseID a INNER JOIN PurchaseID b ON a.PurchaseID=b.PurchaseID
WHERE a.PurchaseID=?
AND a.purchaseDate=?
AND b.purchaseDate=?
使用要比较的ID和日期填写占位符。
请参阅您的DBMS文档,看看您是否有数学absolute function。
答案 1 :(得分:0)
您可能还想添加AND a.purchaseDate <> b.purchaseDate
答案 2 :(得分:0)
SELECT a.purchasePrice AS p1, b.purchasePrice AS p2, a.purchasePrice - b.purchasePrice as difference
from Orders a inner join Orders b on a.PurchaseID = b.PurchaseID
答案 3 :(得分:0)
SELECT ((SELECT purchasePrice FROM Orders WHERE PurchaseID = 1 AND purchaseDate = '2010-06-21') - (SELECT purchasePrice FROM Orders WHERE PurchaseID = 1 AND purchaseDate = '2010-06-20')) AS diff;
答案 4 :(得分:0)
如果您愿意,也可以在查询中执行减法。您可能还想确保在同一天没有购买两件商品:
SELECT a.purchasePrice AS purchasePriceDay1 , b.purchasePrice AS purchasePriceDay2, (purchasePriceDay2-purchasePriceDay1) AS purchasePriceDelta
from Orders a , Orders b
where a.PurchaseID = b.PurchaseID
and a.PurchaseDate < b.PurchaseDate