在添加了几个连接后,我在连接时会得到重复数据和其他数据。有什么想法我可能做错了吗?
没有欺骗的旧代码:
SELECT
dbo.dateonly(ctl.datetrans) AS DateRecorded,
L.Clientkey AS ClientNum,
L.Fullname,
cs.Datesvc,
cs.chargekey,
ctl.CheckNum,
ctl.ReceivedFrom,
ctl.Delta,
CONVERT(varchar(10), dept.deptkey) AS Deptkey,
dept.DeptName,
dept.PgmName,
CONVERT(varchar(10), dept.pgmKey) AS PGMKey,
ctl.Transtypelu
FROM
bil_Chargetranslog ctl
LEFT JOIN dbo.BIL_ChargeSlips cs
ON cs.Chargekey = ctl.Chargekey
LEFT JOIN dbo.BLV_Clients L
ON cs.ClientKey = L.ClientKey
LEFT JOIN Blv_DeptPgm dept
ON dept.Pgmkey = cs.PgmLU
WHERE
(
ctl.Transtypelu = 4
AND (
(
ctl.descr <> 'Client Payment'
AND ctl.descr <> 'Copayment'
) OR ctl.descr IS NULL
)
)
UNION ALL
/* note below that the checknum is converted to a varchar for the query*/
SELECT
dbo.dateonly(daterecorded) AS daterecorded,
L.Clientkey AS ClientNum,
L.Fullname,
DatePayment,
NULL AS chargekey,
CONVERT(varchar(15), checknum) AS checknum,
NULL AS receivedfrom,
(- 1 * Amount) AS delta,
CONVERT(varchar(10), dept.deptkey) AS Deptkey,
dept.DeptName,
dept.PgmName,
CONVERT(varchar(10), dept.pgmKey) AS PGMKey,
4 AS transtypelu
FROM
bil_clientdeposit
LEFT JOIN dbo.BLV_Clients L
ON bil_clientdeposit.ClientKey = L.ClientKey
LEFT JOIN Blv_DeptPgm dept
ON dept.Pgmkey = Bil_ClientDeposit.PgmKey
这是我的新代码:
SELECT
dbo.dateonly(ctl.datetrans) AS DateRecorded,
L.Clientkey AS ClientNum,
L.Fullname,
cs.Datesvc,
cs.chargekey,
ctl.CheckNum,
ctl.ReceivedFrom,
ctl.Delta,
CONVERT(varchar(10), dept.deptkey) AS Deptkey,
dept.DeptName,
dept.PgmName,
CONVERT(varchar(10), dept.pgmKey) AS PGMKey,
ctl.Transtypelu,
pr.PlanName
FROM
bil_Chargetranslog ctl
LEFT JOIN dbo.BIL_ChargeSlips cs
ON cs.Chargekey = ctl.Chargekey
LEFT JOIN dbo.BLV_Clients L
ON cs.ClientKey = L.ClientKey
LEFT JOIN Blv_DeptPgm dept
ON dept.Pgmkey = cs.PgmLU
left join BIL_ARTRANSLOG AR
ON ctl.chargekey = ar.chargekey
left join BIL_PAYORPLANS PR
ON PR.PAYORPLANKEY = AR.PAYORPLANKEY
WHERE
(
ctl.Transtypelu = 4
and ar.TransTypeLU = 4
AND (
(
ctl.descr <> 'Client Payment'
and AR.ARDescr <> 'Client Payment'
AND ctl.descr <> 'Copayment'
and AR.ARDescr <> 'Copayment'
) OR ctl.descr IS NULL
or ar.ARDescr is null
)
)
UNION ALL
/* note below that the checknum is converted to a varchar for the query*/
SELECT
dbo.dateonly(daterecorded) AS daterecorded,
L.Clientkey AS ClientNum,
L.Fullname,
DatePayment,
NULL AS chargekey,
CONVERT(varchar(15), checknum) AS checknum,
NULL AS receivedfrom,
(- 1 * Amount) AS delta,
CONVERT(varchar(10), dept.deptkey) AS Deptkey,
dept.DeptName,
dept.PgmName,
CONVERT(varchar(10), dept.pgmKey) AS PGMKey,
4 AS transtypelu,
NULL as planname
FROM
bil_clientdeposit
LEFT JOIN dbo.BLV_Clients L
ON bil_clientdeposit.ClientKey = L.ClientKey
LEFT JOIN Blv_DeptPgm dept
ON dept.Pgmkey = Bil_ClientDeposit.PgmKey
我添加了以下几行:
left join BIL_ARTRANSLOG AR
ON ctl.chargekey = ar.chargekey
left join BIL_PAYORPLANS PR
ON PR.PAYORPLANKEY = AR.PAYORPLANKEY