根据其他一些列寻找重复项

时间:2015-06-04 20:52:12

标签: sql sql-server

我正在尝试查找PilotID多次使用shimpmentNumber的行。

到目前为止,我有这个。

select f_Shipment_ID
      ,f_date
      ,f_Pilot_ID
      ,f_Shipname
      ,f_SailedFrom
      ,f_SailedTo
      ,f_d_m
      ,f_Shipmentnumber
      ,f_NumberOfPilots
from t_shipment
where f_Pilot_ID < 10000 
  and f_NumberOfPilots=1
  and f_Shipmentnumber in(select f_Shipmentnumber 
                          from t_shipment
                          group by f_Shipmentnumber
                          Having count(*) >1)

3 个答案:

答案 0 :(得分:1)

在子选择中使用:

select f_Shipmentnumber 
                      from t_shipment
                      group by f_pilot_id, f_Shipmentnumber
                      Having count(*) >1

答案 1 :(得分:1)

尝试这样的事情:

-- The CTE determines the f_Pilot_ID/f_Shipmentnumber combinations that appear more than once.
with DuplicateShipmentNumberCTE as
(
    select
        f_Pilot_ID,
        f_Shipmentnumber
    from
        t_shipment
    where
        f_Pilot_ID < 10000 and
        f_NumberOfPilots = 1
    group by
        f_Pilot_ID,
        f_Shipmentnumber
    having
        count(1) > 1
)

select
    Shipment.f_Shipment_ID,
    Shipment.f_date,
    Shipment.f_Pilot_ID,
    Shipment.f_Shipname,
    Shipment.f_SailedFrom,
    Shipment.f_SailedTo,
    Shipment.f_d_m,
    Shipment.f_Shipmentnumber,
    Shipment.f_NumberOfPilots
from
    -- The join is used to restrict the result set to the shipments identified by the CTE.
    t_shipment Shipment
    inner join DuplicateShipmentNumberCTE CTE on
        Shipment.f_Pilot_ID = CTE.f_Pilot_ID and
        Shipment.f_Shipmentnumber = CTE.f_Shipmentnumber
where
    f_NumberOfPilots = 1;

如果您愿意,或者如果您使用的旧版SQL Server不支持CTEs,您也可以使用子查询执行此操作 - 但我发现CTE语法为更自然,只是因为它使您能够从上到下阅读和理解查询,而不是从内到外。

答案 2 :(得分:1)

这个怎么样

select f_Shipment_ID
      ,f_date
      ,f_Pilot_ID
      ,f_Shipname
      ,f_SailedFrom
      ,f_SailedTo
      ,f_d_m
      ,f_Shipmentnumber
      ,f_NumberOfPilots
from t_shipment
where f_Pilot_ID < 10000 
  and f_NumberOfPilots=1
  and f_Pilot_ID  IN (select f_Pilot_ID 
                          from t_shipment
                          group by f_Pilot_ID, f_Shipmentnumber
                          Having count(*) >1)