获取一个字段的最新值,同时分组其他字段

时间:2015-10-29 15:00:52

标签: mysql database

我正在尝试将大批交易“汇总”为更易于管理的尖端数据行。例如:

ID        item        description     qty      unitPrice    extPrice
1234      foo         foo bar          6       10            60
2345      foo         foo bar          2       10            20
3456      foo         foo bar          2       15            30

将分组为另一个表格:

ID        item        description     qty      extPrice     lastPricePaid
1         foo         foo bar          10      110          15

我目前遇到的问题是弄清楚如何确定lastPricePaid值。这是当前查询没有,包括:

SELECT id, groupId, datePurchase, vendor, venItem, item, itemDesc, uom, SUM(qtyPurchase) AS `qtyPurchase`, SUM(extPrice) AS `totalPrice`, MAX(unitPrice) AS `maxPrice`, unitPrice, code, stripped_venitem, MAX(datePurchase) as `maxDate`, SUM(extPrice) as `extPrice`, PONum
FROM transactions t
WHERE (((qtyPurchase)!=0))
GROUP BY groupId, vendor, venItem, item, itemDesc, uom
HAVING datePurchase > (MAX(datePurchase) - DATE_SUB(MAX(datePurchase), INTERVAL 1 YEAR));

真正的诀窍是,由于我要进入Solr,我需要将其转换为单个查询,而不依赖于事后的处理技巧。

感谢您的任何见解!

2 个答案:

答案 0 :(得分:1)

我无法测试它,但是你试过按ID排序吗?这样你就可以获得与id更高的单元相关的unitPrice。

SELECT id, groupId, datePurchase, vendor, venItem, item, itemDesc, uom, SUM(qtyPurchase) AS `qtyPurchase`, SUM(extPrice) AS `totalPrice`, MAX(unitPrice) AS `maxPrice`, unitPrice, code, stripped_venitem, MAX(datePurchase) as `maxDate`, SUM(extPrice) as `extPrice`, PONum, unitPrice as lastPricePaid
FROM transactions t
WHERE (((qtyPurchase)!=0))
GROUP BY groupId, vendor, venItem, item, itemDesc, uom
HAVING datePurchase > (MAX(datePurchase) - DATE_SUB(MAX(datePurchase), INTERVAL 1 YEAR)
order by id desc

答案 1 :(得分:0)

也许有更好的方法,但这对我有用:

SELECT t.id, t.groupId, t.datePurchase, t.vendor, t.venItem, t.item,
 t.itemDesc, t.uom, SUM(t.qtyPurchase) AS `qtyPurchase`, 
SUM(t.extPrice) AS `totalPrice`, MAX(t.unitPrice) AS `maxPrice`,
t.unitPrice, t.code, t.stripped_venitem,
MAX(t.datePurchase) as `maxDate`, SUM(t.extPrice) as `extPrice`, t.PONum , 
t1.unitPrice as 'lastPricePaid'
FROM transactions t, transactions t1
WHERE (((t.qtyPurchase)!=0)) 
AND t1.id = (
      SELECT max(t2.id) FROM transactions t2
)
GROUP BY t.groupId, t.vendor, t.venItem, t.item, t.itemDesc, t.uom
HAVING t.datePurchase > (MAX(t.datePurchase) - DATE_SUB(MAX(t.datePurchase), INTERVAL 1 YEAR));