为什么这个SQL查询返回完全重复的记录?

时间:2015-12-08 06:05:31

标签: sql sql-server sql-server-2008

我写了这个查询,它给了我完全重复的记录。

无法弄清楚原因。需要你的帮助。

我需要知道导致查询显示重复记录的原因。

这是查询,后跟架构。

查询:

select 
    p.Scode Property,
    IsNull(u.Scode, '') Unit,
    IsNull(ISNULL(t.sCode, tr.SD2), '') Payer,
    'R-' + RTrim(LTrim(Convert(Varchar(9), tr.Id-600000000))) Receipt,
    tr.uPDate 'Post Date',
    tr.sDateOccurred 'Date Occurred',
    tr.sTotalAmount 'Total Amount',
    Case tr.sAmountPaid 
       When Null Then '' When 0 Then 0 Else '' 
    End 'Amount Paid'
from 
    P p
INNER JOIN 
    TR tr ON tr.hprop = p.Id
INNER JOIN 
    GT dt ON isnull(tr.HP5,0) = Case when 'Non-P' = 'Non-P' Then 2 else dt.Id end
LEFT JOIN 
    T t on isnull(tr.HPERSON,0) = Case when 'Ten' = 'Non-Ten' Then 0 else t.Id end
LEFT JOIN 
    U u ON u.Id = tr.hUnit
WHERE
    1 = 1
    and p.Id = 99
    and tr.uPDate Between convert(datetime, '01-Apr-2015', 106) And convert(datetime, '01-Apr-2015', 106)
ORDER BY
    p.sCode, u.sCode, t.sCode, tr.SD2, tr.uPDate

架构:

P

Id int Primary key
Scode varchar(20)
...

Ť

Id int Primary Key
Scode varchar(20)
...

û

Id int Primary key
Scode varchar(20)
...

TR

Id bigint Primary Key
hP int FK(P)
hP5 int
hPerson FK(T)
SD2 varchar(20)
hUnit int FK(U)
uPDate Date
...

GT

Id int Primary Key
Scode varchar(20)
...

示例查询输出

lwheight                Laundry     R-1016071   2015-04-01  2015-04-17  350.00  0
lwheight                Laundry     R-1016071   2015-04-01  2015-04-17  350.00  0
lwheight    1104        t0026989    R-1009490   2015-04-01  2015-04-06  832.28  0
lwheight    1104        t0026989    R-1009490   2015-04-01  2015-04-06  832.28  0

1 个答案:

答案 0 :(得分:0)

是。乔纳森是对的。 案件陈述引起了一个问题。 我将查询更改为:

select p.Scode Property,
IsNull(u.Scode, '') Unit,
IsNull(ISNULL(t.sCode, tr.SD2), '') Payer,
'R-' + RTrim(LTrim(Convert(Varchar(9), tr.Id-600000000))) Receipt,
tr.uPDate 'Post Date',
tr.sDateOccurred 'Date Occurred',
tr.sTotalAmount 'Total Amount',
Case tr.sAmountPaid When Null Then '' When 0 Then 0 Else '' End 'Amount Paid'
from P p
INNER JOIN TR tr ON tr.hprop = p.Id
INNER JOIN GT dt ON isnull(tr.HP5,0) = gt.Id and gt.scode = 'z-nonper'
LEFT JOIN T t on isnull(tr.HPERSON,0) = t.Id
LEFT JOIN U u
ON u.Id=tr.hUnit
WHERE
1 = 1
and p.Id=99
and tr.uPDate Between convert(datetime, '01-Apr-2015', 106) And convert(datetime, '01-Apr-2015', 106)
ORDER BY
p.sCode,
u.sCode,
t.sCode,
tr.SD2,
tr.uPDate

它按要求工作。 谢谢。 :)