我正在運行此查詢。從加入表中選擇MAX(日期)
SELECT
t1.quantity,
t2.transaction_date,
t1.product_id
FROM
ezsystem_usah.invoice_line AS t1
INNER JOIN ezsystem_usah.invoices AS t2
ON t1.invoice_id = t2.id_invoices
WHERE
t2.customer_id = '8000004C-1325619329'
AND (product_id = '8000016F-1325198704'
OR product_id = '80000027-1324422404' OR ...);
所得表是:
quantity | transaction_date | product_id
7 2012-01-04 8000016F-1325198704
8 2012-03-05 8000016F-1325198704
1 2012-01-05 11111111-1324422404
... ... ...
我想選擇用於特定PRODUCT_ID基於MAX(TRANSACTION_DATE)行,以產生這樣的事情:
quantity | transaction_date | product_id
8 2012-03-05 8000016F-1325198704
1 2012-01-05 11111111-1324422404
換句話說,從連接表中,我想選擇每個產品ID的最新條目。
我曾嘗試:
SELECT
t1.quantity,
MAX(t2.transaction_date),
t1.product_id
FROM
ezsystem_usah.invoice_line AS t1
INNER JOIN ezsystem_usah.invoices AS t2 ON t1.invoice_id = t2.id_invoices
WHERE
t2.customer_id = '8000004C-1325619329'
AND (product_id = '8000016F-1325198704' OR product_id = '80000027-1324422404' OR ...)
GROUP BY
t1.product_id;
但是數量是不正確。
另一種方法,我沒有嘗試過,但我認爲可能的工作是使用HAVING MAX(transaction_date) = ([sub query])
,但它似乎代價高昂。
最糟糕的情況是,我可以針對每個產品逐個運行查詢,但是如果可能的話,我想避免這種查詢。
感謝, 丹麥
哪個表是transaction_date和product_id中的? – 2012-07-19 21:52:37
謝謝你的擡頭,我添加了信息 – Danedo 2012-07-20 14:28:09