内部连接没有重复值,保留第一个表

时间:2017-07-18 13:45:49

标签: sql sql-server sql-server-2008 inner-join

我有一张桌子,上面写着每张发票的折扣。例如:

Invoice Number|Discount
------------------------
    1         |   3
    2         |   5
    3         |   6

我需要将这些折扣提取到发票行表中(因为它们仅适用于发票总额,而不适用于特定行)。与此同时,我不能失去任何一条线。

示例:如果发票1有5行,我需要显示所有行(发票的5行),但我只想要折扣一次(例如,第一行就足够了)。

预期:

Invoice Number|Discount
------------------------
    1         |   3
    1         |   null
    1         |   null
    1         |   null
    1         |   null

如果我有一个Invoice表,并且InvoiceLines表可以通过两个表中的发票编号加入,我怎样才能得到我需要的结果?

我尝试了此查询但没有成功:

Select  
   ROW_NUMBER() over(order by v.num_fra)as Rank,
   l.*,
   v.ctdrap_div as discount 
from ffac_vta v         --(invoicetable)  
join ffac_hla l         --(invoice lines table)
ON v.num_fra = l.num_fra

你能帮助我吗?

6 个答案:

答案 0 :(得分:1)

以下是另一种方法...基本上,您的子查询会提取行项目信息 - 并获取行号(按订单号分区)。然后,当行号= 1时,您LEFT OUTER JOIN表格的子集仅具有折扣值。此方法不需要CASE语句,因为LEFT OUTER JOIN会给您所有行号都高于1的NULL值。

SELECT  Sub.*, 
        V.ctdrap_div AS [Discount]
FROM 
    (
    SELECT *,
            ROW_NUMBER() OVER(PARTITION BY v.num_fra ORDER BY v.num_fra) AS [Row Number]
    FROM ffac_hla L
    ) Sub
LEFT OUTER JOIN ffac_vta V
    ON v.num_fra = Sub.num_fra
    AND Sub.[Row Number] = 1

答案 1 :(得分:0)

您似乎应该可以将联接更改为左联接。

Select  
  ROW_NUMBER() over(order by v.num_fra)as Rank,
  l.*,
  v.ctdrap_div as discount 
from ffac_vta v         --(invoicetable)  
left join ffac_hla l         --(invoice lines table)
ON v.num_fra = l.num_fra

答案 2 :(得分:0)

您需要使用行表格的键或其他内容来订购行。像这样的东西。另外,我们在SQL-Server-2008中有ROW_NUMBER()吗?

SELECT T.num_fra,
  CASE WHEN T.rank = 1 THEN T.Discount
    ELSE NULL AS Discount
FROM    
(
Select  
   ROW_NUMBER() over(PARTITION BY v.num_fra ORDER BY <<ADD THE KEY OF INVOICE LINES HERE>>)as Rank,
   l.*,
   v.ctdrap_div as discount 
from ffac_vta v         --(invoicetable)  
join ffac_hla l         --(invoice lines table)
ON v.num_fra = l.num_fra
) AS T

答案 3 :(得分:0)

更改为

;WITH cte AS (SELECT DENSE_RANK() over(order by v.num_fra)as Rank,
                num_fra,
                l.*,
                v.ctdrap_div as discount 
              FROM ffac_vta v         --(invoicetable)  
              JOIN ffac_hla l         --(invoice lines table)
                   ON v.num_fra = l.num_fra
)
SELECT num_fra
    , CASE WHEN Rank = 1 THEN discount ELSE 0 END
    , *
FROM cte;

答案 4 :(得分:0)

我认为你可以使用左连接...... 有关加入的详细信息,您可以访问以下网站:https://www.quora.com/SQL-What-is-the-difference-between-various-types-of-joins

difference between join image

我希望这可以帮到你

答案 5 :(得分:-2)

试试这个:

select i.InvoiceID,Discount
from invoicedetail i 
left join invoicediscount id on i.invoiceID=id.invoiceid and i.linenumber=1