这是发票历史表中的数据。
invoicehistoryID WorkOrderNumber InvoiceDate
1 1 2017-06-13 12:00:49
2 1 2017-06-13 12:05:05
3 10 2017-06-14 12:32:59
4 10 2017-06-14 14:26:25
5 1 2017-06-14 14:26:54
6 1 2017-06-22 10:12:49
我需要什么SELECT查询才能获得WorkOrderNumber订购的每个WorkOrderNumber的最新InvoiceDate?换句话说,我怎么能得到这个:
invoicehistoryID WorkOrderNumber InvoiceDate
6 1 2017-06-22 10:12:49
4 10 2017-06-14 14:26:25
我还没有成功使用DISTINCT。我没有成功使用LIMIT因为我的发票历史表会增长。
这几乎可行,
SELECT max(InvoiceDate),WorkOrderNumber FROM `invoicehistory` GROUP BY WorkOrderNumber
但没有获得invoicehistoryID 此
SELECT max(InvoiceDate),WorkOrderNumber, invoicehistoryID FROM `invoicehistory` GROUP BY WorkOrderNumber, invoicehistoryID
返回所有行。
答案 0 :(得分:0)
尝试:
SELECT invoicehistoryID, WorkOrderNumber, InvoiceDate
FROM (SELECT invoicehistoryID, WorkOrderNumber, InvoiceDate
FROM TABLE
ORDER BY WorkOrderNumber ASC, InvoiceDate DESC
) inv
GROUP BY WorkOrderNumber
答案 1 :(得分:0)
通过在日期和订单nubmer上将D加入IH,我们可以在需要时获取缺少的invoicehistoryID和其他信息。
SELECT IH.invoiceHistoryID, IH.WorkOrderNumber, IH.InvoiceDate
FROM InvoiceHistory IH
INNER JOIN (SELECT max(invoiceDate) mInvoiceDate, WorkOrderNumber
FROM invoicehistory
GROUP BY workorderNumber) D
on D.mInvoiceDate = IH.InvoiceDate
and D.WorkOrderNumber = IH.workOrderNumber
如果mySQL支持,则交叉应用将是实现此目的的另一种方式
或使用窗口函数指定行号,并在mySQL支持时将结果限制为最新日期。
答案 2 :(得分:0)
我没有注意到mySql,直到我在ms sql中得到答案:
CREATE TABLE #tmp(
InvoiceHistoryID INT,
WorkOrderNumber INT,
InvoiceDate datetime
)
INSERT INTO #tmp VALUES(1,1,'2017-06-13 12:00:49')
INSERT INTO #tmp VALUES(2,1,'2017-06-13 12:05:05')
INSERT INTO #tmp VALUES(3,10,'2017-06-14 12:32:59')
INSERT INTO #tmp VALUES(4,10,'2017-06-14 12:32:59')
INSERT INTO #tmp VALUES(5,1,'2017-06-14 14:26:54')
INSERT INTO #tmp VALUES(6,1,'2017-06-22 10:12:49')
SELECT
t.InvoiceHistoryID,
t.WorkOrderNumber,
m.InvoiceDate
FROM #tmp t JOIN (SELECT MAX(InvoiceHistoryID) AS InvoiceHistoryID,
MAX(InvoiceDate) AS InvoiceDate
FROM #tmp
GROUP BY WorkOrderNumber ) AS m
ON t.InvoiceHistoryID = m.InvoiceHistoryID
DROP TABLE #tmp