1

我有这个查询:

SELECT pih.PID, piv.TSV, piv.Variable_ID, piv.Value_ID, piv.Manual_Value
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

我明白了:

在此处输入图像描述
我的问题是这些行是重复的,以供我此时使用。是否可以仅在 DISTINCT TSV 上获取行?或类似的东西?

谢谢

4

2 回答 2

2

你可以这样做:

;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.TSVORDER 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
于 2012-11-20T14:38:07.860 回答
0

你想要

SELECT pih.PID,  piv.Variable_ID, piv.Value_ID, piv.Manual_Value
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
group by
pih.PID,  piv.Variable_ID, piv.Value_ID, piv.Manual_Value
于 2012-11-20T15:34:55.560 回答