我有一个查询链接表一两个表二并获得表1中结果的最后一个注释,但是当有一个具有相同ID的表中的多个记录时,它会再次显示结果一个例子
查询结果
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
答案 0 :(得分:1)
你可以使用这样的东西。 使用row_number,您可以按照machnine id对数据进行分区,并按日期对数字进行排序。你可以使用一个简单的clouse来选择你想要的东西
;WITH CTE
as
(
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
) AS Qc
WHERE (Qualitycontrol.CreatedTime BETWEEN CAST(GETDATE() AS DATE) AND DATEADD(DAY, 1, CAST(GETDATE() AS DATE)))
), CTE2 as
(
select *, row_number() over(partition by MachineNo order by CreatedTime desc) as 'row_index' from cte
)
select * from cte2
where row_index = 1
order by MachineNo
答案 1 :(得分: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 = QualityControl_Comments.QCUID
ORDER BY Qualitycontrol.ID DESC -- whatevet defines order in QualityControl_Comments
) AS Qc
INNER JOIN
(
SELECT Qualitycontrol.MachineNo, MAX(Qualitycontrol.ID) MID
FROM Qualitycontrol
GROUP BY Qualitycontrol.MachineNo
) UNQ ON UNQ.MID = Qualitycontrol.ID
WHERE (Qualitycontrol.CreatedTime BETWEEN CAST(GETDATE() AS DATE) AND DATEADD(DAY, 1, CAST(GETDATE() AS DATE)))
ORDER BY Qualitycontrol.MachineNo