我真的很难解释,但我会试试。假设我有以下表格:
CREATE TABLE inventory (
Store VARCHAR(16),
Product_Code INT UNSIGNED,
Inventory_Qty INT UNSIGNED,
`Date` DATE
);
CREATE TABLE Alias (
computername VARCHAR(16),
storename VARCHAR(32),
);
我想创建一个MYSQL查询,该查询根据表中的最后一个条目返回数据。我根据日期使用MAX函数做得很好,但是我需要更高级的查找特定产品输入的最后一项,并返回最后一个数量,即使它不是同一个日期。这是我想要的数据样本:
Store| Product| Qty| Date S1 | 1115 | 10 | 12/30/09 S2 | 1115 | 20 | 12/30/09 S3 | 1115 | 5 | 12/29/09 S4 | 1115 | 15 | 12/28/09
我的查询是这个,但它只返回S1和S2因为我在日期有最大值,但我想要返回所有商店的最新x产品条目:
Select
alias.storename,
inventory.Product_Code,
inventory.Inventory_Qty,
inventory.Date
From inventory
Inner Join Alias On inventory.Store = Alias.computername
Where inventory.Date = (Select Max(inventory.Date) From inventory)
Order By Alias.storename, inventory.Product_Code
非常感谢任何帮助
答案 0 :(得分:2)
看看
SELECT i.*
FROM (
SELECT Store,
Product,
MAX(Date) MaxDate
FROM inventory
GROUP BY Store,
Product
) MaxDates INNER JOIN
inventory i ON MaxDates.Store = i.Store
AND MaxDates.Product = i.Store
AND MaxDates.MaxDate = i.Date
这将首先获得每商品每商店的最长日期,然后返回最后<< / strong>进入。
如果我误解了您的请求,请告诉我。
答案 1 :(得分:1)
如果您希望为每个商店输入最新的记录,那么
Select a.storename,
i.Product_Code, i.Inventory_Qty, i.Date
From Alias a
left Join inventory i
On i.Store = a.computername
and i.Date =
(Select Max(Date)
From inventory
Where Store = i.Store)
Order By a.storename, i.Product_Code
答案 2 :(得分:0)
我相信这会让你得到你想要的东西:
SELECT
alias.storename,
inventory.Product_Code,
inventory.Inventory_Qty,
lastdate.date
FROM (
SELECT
store,
max(date) as date
FROM inventory
GROUP BY store
) lastdate
INNER JOIN inventory
ON inventory.store = lastdate.story
AND inventory.date = lastdate.date
INNER JOIN alias
ON inventory.store = alias.computername
ORDER BY
alias.storename,
inventory.Product_Code
这将获得每家商店在该商店出售任何商品的最后日期销售的所有商品。