第一步:獲取詳細信息表創建一個過濾器
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`
非常感謝Eugen。我一回到家就會嘗試。邏輯似乎是我正在尋找的。 – Josef 2012-02-15 09:41:13
尤普,你真了不起!最後我的問題解決了:) – Josef 2012-02-15 17:47:06