摆脱连接的SQL查询中的重复

时间:2017-04-24 20:58:44

标签: sql sql-server tsql

我想知道是否有任何方法可以摆脱它创建的重复行信息,以便在一个表中有2个项目时填充结果中的空间,但在另一个表中只有1个项目。我尝试过不同的联盟和一组人,而且都没有。我认为我需要某种嵌套子查询或某种限制或rownum = 1条件。感谢您提供任何帮助。

我的代码:

select distinct
    Driver_Extra_Pay.Order_ID as 'Order',
    Deduct_Code_ID as 'D/E Code',
    Short_Desc as 'Pay Description',
    Driver_Extra_Pay.Amount as 'Pay Amount',
    Driver_Extra_Pay.Amount_D as 'Pay Date',
    Other_Charge.Descr as 'Charge Description',
    Other_Charge.Amount as 'Charge Amount',
    Other_Charge.Amount_D as 'Charge Date'

from
    Driver_Extra_Pay
inner join
    Other_Charge on Other_Charge.Order_ID = Driver_Extra_Pay.Order_ID

where Driver_Extra_Pay.Amount_D between '03/29/2016' and '03/30/2016'

order by Driver_Extra_Pay.Order_ID

这是我得到的结果。它以这种方式编写,用作比较工具,但它提供了双倍" Lumper"当只有1时的条目。看起来它只是复制它以填充该空白区域。

enter image description here

我希望它在输出上看起来像这样,但我不知道编码是为了实现它。

enter image description here

1 个答案:

答案 0 :(得分:1)

您希望显示数据的方式在SQl中不起作用。如果需要,可以在表示层中以这种方式显示它。但由于其他费用似乎与驾驶员额外费用没有直接关系,或许您真正需要获得正确数据的是UNION ALL。这将返回两个表中该日期范围的所有费用,以便以后在需要时更容易求和。

    SELECT * 
    FROM 
    (select distinct
        Driver_Extra_Pay.Order_ID as 'Order',
        Deduct_Code_ID as 'D/E Code',
        Short_Desc as 'Description',
        Driver_Extra_Pay.Amount as 'Amount',
        Driver_Extra_Pay.Amount_D as 'Date'
    from
        Driver_Extra_Pay
    where Driver_Extra_Pay.Amount_D between '03/29/2016' and '03/30/2016'
    UNION ALL
    select distinct
       Other_Charge.Order_ID as 'Order',
       'Other' as 'D/E Code',
       Other_Charge.Descr ,
       Other_Charge.Amount,
       Other_Charge.Amount_D,
    from
        Other_Charge 
    where  Other_Charge .Amount_D between '03/29/2016' and '03/30/2016') a
    order by [Order]

此查询将报告其他没有相应的驱动程序额外支付记录的费用(您当前的查询不会记录。)如果您需要,请尝试以下操作:

SELECT * 
FROM 
(select distinct
    Driver_Extra_Pay.Order_ID as 'Order',
    Deduct_Code_ID as 'D/E Code',
    Short_Desc as 'Description',
    Driver_Extra_Pay.Amount as 'Amount',
    Driver_Extra_Pay.Amount_D as 'Date'
from
    Driver_Extra_Pay
where Driver_Extra_Pay.Amount_D between '03/29/2016' and '03/30/2016'
UNION ALL
select distinct
   Other_Charge.Order_ID as 'Order',
   'Other' as 'D/E Code',
   Other_Charge.Descr ,
   Other_Charge.Amount,
   Other_Charge.Amount_D,
from
    Driver_Extra_Pay
inner join
    Other_Charge on Other_Charge.Order_ID = Driver_Extra_Pay.Order_ID
where Driver_Extra_Pay.Amount_D between '03/29/2016' and '03/30/2016') a
order by [Order]