如何找到两个选定日期的价格差异。我的表格如图所示
---------------------------------------
id price date product
---------------------------------------
1 10 15-12-2013 pen
2 40 15-12-2013 book
3 15 16-12-2013 pen
4 42 16-12-2013 book
-------------------------------------
我希望sql查询得到输出,如果startdate:15-12-2013& enddate:16-12-2013
product startdate(15-12-2013) enddate(16-12-2013) difference
--------------------------------------------------------------
pen 10 15 5
book 40 42 2
--------------------------------------------------------------
答案 0 :(得分:2)
也许是这样的?
select
p1.product,
p1.price,
p2.price,
p1.price - p2.price as diff
from
product p1,
product p2
where
p1.product=p2.product and
date(p1.date)='2013-12-15' and
date(p2.date)='2013-12-16'
如果效果是一个问题,那么此链接可以为日期匹配部分提供更好的选择:MySQL SELECT WHERE datetime matches day (and not necessarily time)
答案 1 :(得分:1)
试试这个:
SELECT product, StartDatePrice, EndDatePrice, (EndDatePrice - StartDatePrice) AS Difference
FROM (SELECT product, MAX(IF(a.date = '15-12-2013', a.price, 0)) AS StartDatePrice,
MAX(IF(a.date = '16-12-2013', a.price, 0)) AS EndDatePrice
FROM tableA a
GROUP BY product
) AS A;
答案 2 :(得分:0)
如果您在价格表上插入一行,那么价格会发生变化,而不是每天都有,您应该考虑使用此查询:
SELECT
p1.product,
p1.price as stardtade,
p2.price as enddate,
p2.price-p1.price as difference
FROM
prices p1 INNER JOIN (SELECT product, MAX(dt) max_dt
FROM prices
WHERE dt<='2013-12-15'
GROUP BY product) st
ON p1.product=st.product AND p1.dt = st.max_dt
INNER JOIN
prices p2
ON p1.product=p2.product
INNER JOIN (SELECT product, MAX(dt) max_dt
FROM prices
WHERE dt<='2013-12-16'
GROUP BY product) ed
ON p2.product=ed.product AND p2.dt = ed.max_dt
它更复杂,但即使您的表中没有某些日期,它也会起作用。在这种情况下,它将使用lask已知值作为价格。
请参阅小提琴here。