你可以这样做:
;WITH CTE
AS
(
SELECT
pih.PID,
piv.TSV,
piv.Variable_ID,
piv.Value_ID,
piv.Manual_Value,
ROW_NUMBER() OVER (PARTITION BY piv.TSV ORDER BY pih.PID) rownum
FROM Process_Instance_Value AS piv
INNER JOIN Process_Instance_History AS pih ON piv.PID = pih.PID
WHERE piv.Variable_ID IN ( SELECT Variable_ID
FROM someTable
WHERE Transition_ID = @someValue)
AND piv.PID = @someValue
)
SELECT *
FROM CTE
WHERE rownum = 1;
请注意:如果您想要最大值,这将返回pih.PID
每个不同的最小值,只需使用。piv.TSV
ORDER BY pih.PID DESC
这是如何运作的:
排名函数ROW_NUMBER() OVER()
将为在 中列出的具有相同列的每个组提供一个排名编号PARTITION BY
,在我们的例子piv.TSV
中,对于每个组,这个排名编号将根据ORDER BY
子句中定义的OVER
子句进行排序,在我们的例子ORDER BY pih.PID
中。我使用CTE而不是使用子查询。
然后我用WHERE rownum = 1
了 ,因为rownum
每组piv.TSV
排名相同的记录都按照降序给出了排名号,那么带有的记录rownum = 1
将是最小的记录pih.PID
(想想看)。
但是,您可以使用内部联接获得相同的结果,GROUP BY
如下所示:
SELECT
pih.PID,
piv.TSV,
piv.Variable_ID,
piv.Value_ID,
piv.Manual_Value
FROM Process_Instance_Value AS piv
INNER JOIN
(
SELECT
TSV, MIN(PID) MinPID
FROM Process_Instance_Value
GROUP BY TSV
) piv2 ON piv.PID = piv2.MinPID
INNER JOIN Process_Instance_History AS pih ON piv.PID = pih.PID
WHERE piv.Variable_ID IN ( SELECT Variable_ID
FROM someTable
WHERE Transition_ID = @someValue)
AND piv.PID = @someValue