2

以下 Query 为我返回了 column 具有多个值的数据FM.FaultIDMSTR,我想消除重复并只取一个值并沿该值显示其他数据。

Select TOP 1000 
  FH.AtmKey,F.FAULTDESC,FH.FAULTSTARTTIME,FH.FAULTENDTIME,FM.FaultIDMSTR
From FAULTS_HISTORY FH, FAULTDEFS F, FAULTMAP FM 
where FH.FaultID = F.FAULTID
and F.FAULTID = FM.FaultID
and FH.AtmKey in ('11487676154140993')

在此处输入图像描述

消除重复的条件将基于从 column 派生的较大值FH.FAULTSTARTTIME

我不确定如何通过多个连接来实现这种级别的分组,这是我的查询

4

1 回答 1

2

You can use the ranking function ROW_NUMBER() OVER(PARTITION BY ... ORDER BY ... like this:

WITH CTE
AS
(
    Select TOP 1000 
      FH.AtmKey,
      F.FAULTDESC,
      FH.FAULTSTARTTIME,
      FH.FAULTENDTIME,
      FM.FaultIDMSTR,
      ROW_NUMBER() OVER(PARTITION BY FM.FaultIDMSTR
                        ORDER BY FH.FAULTSTARTTIME DESC) AS RN
    From FAULTS_HISTORY FH
    INNER JOIN FAULTDEFS F ON FH.FaultID = F.FAULTID
    INNER JOIN FAULTMAP FM ON F.FAULTID = FM.FaultID
    where FH.AtmKey in ('11487676154140993')
)
SELECT 
  AtmKey,
  AULTDESC,
  FAULTSTARTTIME,
  FAULTENDTIME,
  FaultIDMSTR
FROM CTE
WHERE RN = 1;

This will give you the rows with maximum of FH.FAULTSTARTTIME for each FM.FaultIDMSTR, if you want to group by another column put it in the PARTITION BY column.

Note that: Try to avoid the old JOIN syntax, and use the ANSI-92 syntax, see this:

于 2013-09-10T07:52:17.523 回答