我有一個查詢鏈接表一個兩個表二,並獲得結果在表一最後的評論,這工作,但是當有多個記錄從表一個與例如,它再次說明,因此這裏的同一個ID就是一個例子刪除重複的行,如果其中一列是相同的Sql服務器
的查詢結果,
ID | Machine | description | createdtime | product code | work order | qty | comment | Reson
No
129 |1 | A name | 2015-01-08 07:38:41.427 | A code | 12/14/0038 | 4000 | comment | Reason
143 |1 | A name | 2015-01-08 13:30:39.403 | A code | 12/14/0038 | 4000 | comment | Reson
130 |4 | A name | 2015-01-08 07:38:46.540 | A code | 12/14/0045 | 12000 | comment | Reason
131 |5 | A name | 2015-01-08 07:38:50.243 | A code | 01/15/0001 | 4000 | comment | Reason
正如你可以看到這裏有兩個記錄與機號1,一個在上午創建一個在中午後,但我只想要最新的一個出現,這是我的查詢。
SELECT Qualitycontrol.ID, Qualitycontrol.MachineNo, Qualitycontrol.Description, Qualitycontrol.CreatedTime, Qualitycontrol.ProductCode, Qualitycontrol.WorkOrder,
Qualitycontrol.Quantity, Qc.Comment, Qc.Reason
FROM Qualitycontrol
OUTER APPLY (
SELECT TOP 1 *
FROM QualityControl_Comments
WHERE Qualitycontrol.ID = QCUID
ORDER BY Qualitycontrol.ID DESC -- whatevet defines order in QualityControl_Comments
) AS Qc
WHERE (Qualitycontrol.CreatedTime BETWEEN CAST(GETDATE() AS DATE) AND DATEADD(DAY, 1, CAST(GETDATE() AS DATE)))
ORDER BY Qualitycontrol.MachineNo
嘗試完全限定QCUID - 即在外部應用範圍中使用** QualityControl_Comments.QCUID **。否則我沒有看到有什麼問題 – Madison
問題是,這是拉的所有記錄的一天,但是我只想要最新的一天,關於評論表的部分是好的 –
啊,我的壞。這可能會幫助你:http://dba.stackexchange.com/questions/17217/returning-a-result-set-with-multiple-rows-based-on-max-date – Madison