2016-02-12 64 views
0

我有一个前段时间写过的查询返回一个计数。我现在想看看正在计算的行,但我似乎无法正确地查询我的查询。这是返回计数的查询。获取没有重复的行

select count(distinct f_Shipmentnumber) from t_shipment shipment 
    join t_Pilot pilot on pilot.f_PilotID=shipment.f_Pilot_ID 
    where pilot.f_ProviderID='12' and shipment.f_ShipmentType=2 
    and shipment.f_date > DATEADD(yy, DATEDIFF(yy,0,getdate()), 0) 

这里是我想出了,但它返回重复的装运数量

select * from t_shipment shipment 
    join t_Pilot pilot on pilot.f_PilotID=shipment.f_Pilot_ID 
    where pilot.f_ProviderID='12' and shipment.f_ShipmentType=2 
    and shipment.f_date > DATEADD(yy, DATEDIFF(yy,0,getdate()), 0) 

任何帮助将是巨大的。谢谢!!

+0

那么你想看到当同一批货有一个以上的飞行员是什么? –

+0

我只想看到shipmentNumber一次 –

回答

1

基于在评论你的答案,我认为当有与货物有关的多个试点,你不关心哪个飞行员得到的返回结果。在这种情况下,你可以用一个CTE和ROW_NUMBER()函数解决这个问题:

WITH cte AS (
    select * 
    , ROW_NUMBER() OVER (PARTITION BY f_Shipmentnumber ORDER BY f_Shipmentnumber) AS rn 
    from t_shipment shipment 
    join t_Pilot pilot on pilot.f_PilotID=shipment.f_Pilot_ID 
    where pilot.f_ProviderID='12' and shipment.f_ShipmentType=2 
    and shipment.f_date > DATEADD(yy, DATEDIFF(yy,0,getdate()), 0) 
) 
SELECT * FROM CTE WHERE rn=1 
+0

谢谢Tab !!,这是做的伎俩。 –

+0

还有一个问题。我怎样才能从货运表中返回价值?它返回两个表中的所有值。我试过使用内部连接,但它不工作。 –

+0

而不是'SELECT *',你可以做'SELECT shipment。*'这是在查询顶部的第一个SELECT中。不是底部的那个。 –

0

您必须使用group by,但在group by中,必须按所有列进行分组,并且必须决定要在其他列上返回哪个值。有些事情是这样的:

select f_Shipmentnumber,f_ProviderID,f_ShipmentType,Max(f_date) from t_shipment shipment 
join t_Pilot pilot on pilot.f_PilotID=shipment.f_Pilot_ID 
where pilot.f_ProviderID='12' and shipment.f_ShipmentType=2 
and shipment.f_date > DATEADD(yy, DATEDIFF(yy,0,getdate()), 0) 
group by f_Shipmentnumber,f_ProviderID,f_ShipmentType 
+0

谢谢Veen,这不起作用。货件号码被多次使用。我想要符合条件但没有重复shipmentNumber的所有行。我现在得到这个错误Msg 144,Level 15,State 1,Line 12 不能在用于GROUP BY子句的group by列表的表达式中使用聚合或子查询。 –

+0

我很抱歉,我犯了一个小错误。请尝试下面的 –