使用coalesce双倍记录返回的数量

时间:2017-06-22 12:53:23

标签: sql sql-server

我在下面有两个问题。第一个查询返回83行,这是我所期望的。查询2虽然返回166行(因此第一个查询加倍)。唯一的区别显示在下面的pf和pc中的select语句中,

查询1     SEDOL

查询2     Coalesce(ISIN,Sedol,BbergTicker)Id

我不明白为什么这会使返回的行数翻倍?

查询1

;with pf as
(
    select Name, Sedol, Nominal, FundCode, FileCode 
    from tbl1L where FundCode = 'BUNM' and CashItem = 0 and FileCode in ('MAIN', 'REISTD')
), pc as
(
    select Name, Sedol, Nominal, FundCode, FileCode 
from tbl1C where FundCode = 'BUNM' and CashItem = 0 and FileCode in ('MAIN', 'REDIST')
)
select coalesce(pf.FundCode, pc.FundCode) Fund, coalesce(pf.FileCode, pc.FileCode) FileCode, 
coalesce(pf.Name, pc.Name) Name, coalesce(pf.Sedol, pc.Sedol) Sedol, 
isnull(pf.Nominal, 0) PfNom, isnull(pc.Nominal, 0) PcNom, 
isnull(isnull(pf.Nominal, 0) - isnull(pc.Nominal, 0), -999) NomDiff
from pf full outer join pc on pf.Sedol = pc.Sedol and pf.FileCode = pc.FileCode 
where isnull(isnull(pf.Nominal, 0) - isnull(pc.Nominal, 0),-999) <> 0

查询2

;with pf as
(
    select Name, Coalesce(ISIN, Sedol, BbergTicker) Id, Nominal, FundCode, FileCode 
    from tbl1L where FundCode = 'BUNM' and CashItem = 0 and FileCode in ('MAIN', 'REISTD')
), pc as
(
    select Name, Coalesce(ISIN, Sedol, BbergTicker) Id, Nominal, FundCode, FileCode 
from tbl1C where FundCode = 'BUNM' and CashItem = 0 and FileCode in ('MAIN', 'REDIST')
)
select coalesce(pf.FundCode, pc.FundCode) Fund, coalesce(pf.FileCode, pc.FileCode) FileCode, 
coalesce(pf.Name, pc.Name) Name, coalesce(pf.Id, pc.Id) Id, coalesce(pf.Sedol, pc.Sedol) Sedol, 
isnull(pf.Nominal, 0) PfNom, isnull(pc.Nominal, 0) PcNom, 
isnull(isnull(pf.Nominal, 0) - isnull(pc.Nominal, 0), -999) NomDiff
from pf full outer join pc on pf.Id = pc.Id and pf.FileCode = pc.FileCode 
where isnull(isnull(pf.Nominal, 0) - isnull(pc.Nominal, 0),-999) <> 0

1 个答案:

答案 0 :(得分:3)

查询1:

QSlider::groove

查询2:

pf.Sedol = pc.Sedol and pf.FileCode = pc.FileCode

在联接中,两个查询都有所不同。

合并不会影响记录中的计数