使用带有INNER JOIN的{DISTINCT

时间:2017-10-19 12:18:53

标签: sql sql-server tsql distinct

我目前使用INNER JOIN加入了9列 但我现在想要删除第1列中的重复项,即 CIFnumber

如果我在查询顶部使用DISTINCT,它将无法运行。

我该怎么办?

select distinct
    c.CIFNumber,c.FirstName,c.Surname,c.FamilyID,a.AccountID,
    b.V‌​aluationAmount,d.NAM‌​E,ad.ID_Number,f.PrP‌​lanner 
from
    CUSTOMERINFORMATIONFILETBL c
inner join ACCOUNTTBL a on c.CIFNumber=a.CIFNumber
inner join BALANCETBL b on a.AccountID=b.AccountID
inner join FAMILYTBL f on c.FamilyID= f.FamilyID
inner join DIVISION d on f.DIVISION=d.ID
inner join ADDRESSTBL ad on c.CIFNumber=ad.CIF 
where
    b.ValuationDate = '2017-09-30' and
    d.name = 'Wealth Management' and
    (
        ad.ID_Number= '' or
        ad.ID_Number is null or
        LEN(ad.ID_Number) < 13
    )

2 个答案:

答案 0 :(得分:0)

DISTINCT执行功能 - 它删除特定SELECT语句中列集的重复项。如果DISTINCT没有删除列集中特定列的重复项,则表示您在其他列中具有唯一值。

如果您只需要特定列中的一个唯一值而不关心其他列值,则可以使用窗口函数。

   select *
   from (
    select c.CIFNumber,c.FirstName,..., 
    row_number() over (partition by c.CIFNumber order by [some logic]) as rn
    from...) as a 
    where rn = 1

答案 1 :(得分:0)

您的至少一个列中有两个或更多不同的值。如果您不关心某些数据,可以使用TOP 1 WITH TIES + ROW_NUMBER

this.http.get<Card[]>('https://api.hearthstonejson.com/v1/21517/enUS/cards.collectible.json').subscribe(data => {
  console.log(data[0]); // first card
  console.log(data); // all cards
});

在我的示例中,我希望select top 1 with ties c.CIFNumber, c.FirstName, c.Surname, c.FamilyID, a.AccountID, b.V‌​aluationAmount, d.NAM‌​E, ad.ID_Number, f.PrP‌​lanner from CUSTOMERINFORMATIONFILETBL c inner join ACCOUNTTBL a on c.CIFNumber=a.CIFNumber inner join BALANCETBL b on a.AccountID=b.AccountID inner join FAMILYTBL f on c.FamilyID= f.FamilyID inner join DIVISION d on f.DIVISION=d.ID inner join ADDRESSTBL ad on c.CIFNumber=ad.CIF where b.ValuationDate = '2017-09-30' and d.name = 'Wealth Management' and ( ad.ID_Number= '' or ad.ID_Number is null or LEN(ad.ID_Number) < 13 ) ORDER BY ROW_NUMBER() OVER (PARTITION BY c.CIFNumber, c.FirstName, c.Surname, c.FamilyID ORDER BY (SELECT NULL)) 是唯一的。