添加要查询的列而不更改现有查询的结果

时间:2017-03-09 18:53:21

标签: sql-server

我有一个看起来像这样的查询

WITH A   -- Get a list of unique combinations of Shipmentnumber and ShipmentType
AS  (
SELECT Distinct
      f_Shipmentnumber
 ,    f_ShipmentType
FROM  t_shipment, t_pilot where t_Pilot.f_ProviderID='11' and f_date >='2016-01-01' and f_date <='2017-01-01'
)
,   B  -- Get a list of all those shipmentnumbers values that have more than one shipmentType associated
AS  (
SELECT f_Shipmentnumber
FROM   A
GROUP BY
       f_Shipmentnumber
HAVING COUNT(*) > 1
)
SELECT 
     A.f_Shipmentnumber,
    A.f_ShipmentType

这正是我需要的东西,但现在我需要添加更多的列,例如date,pilotID和其他几个。当我尝试添加它时,它会更改返回的行数。如何在不丢弃结果的情况下添加它们。

以下是返回数据的一小部分示例。

f_Shipmentnumber    f_ShipmentType
   22060    1
   22494    2
   22494    1
   22620    2
   22620    1
   22844    1
   22844    2
   23528    1
   23528    2
   286084   1
   286084   2
   286104   2
   286104   1

该表有很多列,但我想返回上面的数据以及随之而来的其他数据。例如f_Shipment_ID,f_date,f_Pilot_ID,f_imo。 f_shipment_ID是唯一的。我希望这能让你更好地了解我正在做的事情。

我已经做了一些工作,我现在离这里更近了。

WITH A   -- Get a list of unique combinations of Shipmentnumber and          ShipmentType
AS  ( 
 SELECT Distinct
 f_Shipmentnumber, f_ShipmentType, f_Shipment_ID, f_date, f_Pilot_ID,   f_SailedFrom, f_SailedTo
  FROM  t_shipment 
  join t_Pilot pilot on pilot.f_PilotID=t_shipment.f_Pilot_ID 
where pilot.f_ProviderID='11' and t_shipment.f_date >='2016-01-01' and    t_shipment.f_date <='2017-01-01'
)
,   B  -- Get a list of all those shipmentnumbers values that have more than  one shipmentType associated
AS  (
SELECT f_Shipmentnumber
FROM   A
GROUP BY
       f_Shipmentnumber
HAVING COUNT(*) > 1
)
SELECT 
     A.f_Shipment_ID, A.f_Pilot_ID, A.f_Shipmentnumber
,    A.f_ShipmentType, A.f_date, f_SailedFrom, f_SailedTo
FROM    A
JOIN B
    ON  A.f_Shipmentnumber = B.f_Shipmentnumber

以下是返回数据的示例。

f_Shipment_ID   f_Pilot_ID  f_Shipmentnumber    f_ShipmentType  f_date  f_SailedFrom    f_SailedTo
198084  216 286506  2   2016-01-05 11:00:00.000 Kadetrenden 1   Skagen 3 -- P/B
198504  1   286506  2   2016-01-05 11:00:00.000 Kadetrenden 1   Skagen 3 -- P/B
200266  77  286511  1   2016-01-07 10:00:00.000 Langeland T -- P/B  Skagen 3 -- P/B
198538  275 286511  2   2016-01-08 11:00:00.000 Kadetrenden 1   Skagen 3 -- P/B
198130  160 286524  1   2016-01-07 02:00:00.000 Korsør -- P/B   Nyborg Havn
198134  120 286524  1   2016-01-06 04:00:00.000 Langeland H -- P/B  Nyborg -- P/B
199111  45  286524  1   2016-01-06 03:00:00.000 Langeland H -- P/B  Nyborg -- P/B
198081  271 286531  2   2016-01-06 05:00:00.000 Korsør -- P/B   Alfa/4 -- P/B

此时我只想显示具有重复shimpmentNumbers和不同货件类型的行,这是我在添加额外字段之前获得的。具有相同出货类型的重复出货数量需要去。谢谢!!

0 个答案:

没有答案