我在两个不同的表中有价格并且想要减去它们(当前价格 - 最后一天价格)并以DESC形式对它们进行订购。我想知道是否可以使用单个MySQL命令完成。
表格结构
Table 1
id | Item Name | Date | Price
1 | alpha | 2011-10-05 | 10
2 | beta | 2011-10-05 | 12
3 | gamma | 2011-10-05 | 14
Table 2
id | Item Name | Date | Price
1 | alpha | 2011-10-04 | 8
2 | beta | 2011-10-04 | 10
3 | gamma | 2011-10-04 | 12
4 | alpha | 2011-10-03 | 4
5 | beta | 2011-10-03 | 6
6 | gamma | 2011-10-03 | 8
答案 0 :(得分:5)
SELECT
table1.id, table1.`Item Name`,
table1.`Date` AS CurrDate, table1.Price AS CurrPrice,
table2.`Date` AS PrevDate, table2.Price AS PrevPrice,
table1.Price - table2.Price AS Difference
FROM table1
LEFT JOIN table2 ON table1.id = table2.id AND table1.`Date` - INTERVAL 1 DAY = table2.`Date`
ORDER BY Difference DESC
除了我使用LEFT JOIN的方式之外,这个查询没有什么特别之处。我相信如果昨天的记录费率不可用,最后三列将包含NULL。输出:
id | Item Name | CurrDate | CurrPrice | PrevDate | PrevPrice | Difference
2 | beta | 2011-10-05 | 12 | 2011-10-04 | 10 | 2
3 | gamma | 2011-10-05 | 14 | 2011-10-04 | 12 | 2
1 | alpha | 2011-10-05 | 10 | 2011-10-04 | 8 | 2
答案 1 :(得分:4)
SELECT
a.price as price1
, IFNULL(b.price,'(no data)') as price2
, (a.price - IFNULL(b.price,0)) as difference
FROM table1 a
LEFT JOIN table2 b ON (a.`item name` = b.`item name`)
GROUP BY a.`item name`
HAVING IFNULL(b.`date`,'') = MAX(IFNULL(b.`date`,'')
这是它的工作原理。
它从2个表中选择数据:来自table1的所有数据和来自table2的匹配数据
如果找不到table2中的匹配数据,它将替换null
值代替缺失的行。 (left join
)
然后根据group by
将(table1.item name
)行分组在一起。
这样每个项目组合多行
having
子句通过仅选择table2中的最新日期行来解决此问题。
在select
和having
子句中构建一个小的更正来处理table2中没有与table1匹配的数据的情况。
您的查询应该是:
SELECT
s.closing as price1
, IFNULL(sh.closing,'(no data)') as price2
, (s.closing - IFNULL(sh.closing,0)) as difference
FROM stocks s
LEFT JOIN stockhistory sh ON (s.symbol = sh.symbol)
GROUP BY s.symbol
HAVING IFNULL(sh.edate,'') = MAX(IFNULL(sh.edate,'')
LIMIT 30 OFFSET 0;