2012-09-10 79 views
5

在一個簡單的庫存管理數據庫中,新庫存的數量被添加併發貨,直到數量達到零。每個庫存移動都分配一個參考,只使用最新的參考。關聯多個條件的GROUP BY和LEFT JOIN以顯示最新記錄?

在提供的示例中,最新的參考資料從不顯示,股票ID 1,4應分別具有引用charlie,foxtrot,而是顯示alpha,delta。

GROUP BY和LEFT JOIN如何關聯多個條件以顯示最新記錄?

http://sqlfiddle.com/#!2/6bf37/107

CREATE TABLE stock (
    id tinyint PRIMARY KEY, 
    quantity int, 
    parent_id tinyint 
); 

CREATE TABLE stock_reference (
    id tinyint PRIMARY KEY, 
    stock_id tinyint, 
    stock_reference_type_id tinyint, 
    reference varchar(50) 
); 

CREATE TABLE stock_reference_type (
    id tinyint PRIMARY KEY, 
    name varchar(50) 
); 

INSERT INTO stock VALUES 
(1, 10, 1), 
(2, -5, 1), 
(3, -5, 1), 
(4, 20, 4), 
(5, -10, 4), 
(6, -5, 4); 

INSERT INTO stock_reference VALUES 
(1, 1, 1, 'Alpha'), 
(2, 2, 1, 'Beta'), 
(3, 3, 1, 'Charlie'), 
(4, 4, 1, 'Delta'), 
(5, 5, 1, 'Echo'), 
(6, 6, 1, 'Foxtrot'); 

INSERT INTO stock_reference_type VALUES 
(1, 'Customer Reference'); 

SELECT stock.id, SUM(stock.quantity) as quantity, customer.reference 
FROM stock 
LEFT JOIN stock_reference AS customer ON stock.id = customer.stock_id AND stock_reference_type_id = 1 
GROUP BY stock.parent_id 

回答

1

您可以使用子查詢來拉每隻股票組最新的ID:

SELECT g.parent_id, g.quantity, customer.reference 
FROM (
    SELECT parent_id, SUM(stock.quantity) as quantity, MAX(id) as LatestID 
    FROM stock 
    GROUP BY parent_id 
) g LEFT JOIN stock_reference AS custome 
    ON g.LatestID = customer.stock_id AND stock_reference_type_id = 1 
+2

打我給它。 http://sqlfiddle.com/#!2/4edd4/1 – Kermit