2012-02-14 82 views
0

好吧,經過3-4天試圖解決這個問題,我放棄了。 我開始時只有一張桌子,但現在我已經改變了很多,所以我能夠有兩張桌子,我認爲這會讓像我這樣的菜鳥更容易。 See my earlier post here加入和計算問題

取而代之發佈的所有表的細節在這裏我提供一個截圖: Tables and expected result

我已設法取得相當大的本,但問題是,我無法做到不包括計算不應包含的批次。

我該如何解決這個問題?我非常感謝我從你們那裏得到的幫助。 在此先感謝

回答

1

第一步:獲取詳細信息表創建一個過濾器

SELECT 
    MAX(id) AS id 
FROM details 
GROUP BY `concat`, `batch` 

下一步:使用該查詢詳細信息表

SELECT * FROM details 
WHERE id IN (
    SELECT 
     MAX(id) AS id 
    FROM details 
    GROUP BY `concat`, `batch` 
) 

下一步:使用此派生表加入主表爲您的最終結果

SELECT 
    `master`.id AS id, 
    `master`.plant AS plant, 
    `master`.`code` AS `code`, 
    COUNT(*) AS distinct_batches, 
    SUM(filtereddetails.volume) AS total_vol, 
    SUM(filtereddetails.`value`) AS total_val, 
    SUM(filtereddetails.volume*filtereddetails.risk) AS risk_vol, 
    SUM(filtereddetails.`value`*filtereddetails.risk) AS risk_val, 
    MAX(filtereddetails.end_date-filtereddetails.start_date) AS max_date_diff 
FROM 
    `master` 
    INNER JOIN (
    SELECT * FROM details 
    WHERE id IN (
     SELECT 
      MAX(id) AS id 
     FROM details 
     GROUP BY `concat`, `batch` 
    ) 
) AS filtereddetails ON `master`.`concat`=filtereddetails.`concat` 
GROUP BY 
    `master`.`concat` 
+0

非常感謝Eugen。我一回到家就會嘗試。邏輯似乎是我正在尋找的。 – Josef 2012-02-15 09:41:13

+0

尤普,你真了不起!最後我的問題解決了:) – Josef 2012-02-15 17:47:06