我有两张桌子 - 支票和政策。以下是结构。为清楚起见,这是最低限度的结构
表名:检查
列: ChequeId。 支票号码, 量, LASTUPDATED
表名:政策
列 PolicyId, 保单号码, ChequeId, 量, LASTUPDATED
我想要一个回复
的查询ChequeNumber,PolicyId,ChequeAmount,PolicyAmount,Difference
一个检查可以映射到多个策略(一对多关系) 现在,如果检查匹配说2个政策并且这两个政策的金额总和大于支票金额,我应该看到差异,但仅限于第二个政策。它假设第一个政策完全匹配。(也许使用最后更新的列??)所以输出将是
ChequeNumber PolicyNumber ChequeAmount PolicyAmount Difference
1 1 200 100 0
1 2 200 200 100
以下是我所写的内容
SELECT chequeNumber AS chequeNumber
,COALESCE(p.policyNumber, '') AS PolicyNumber
,c.amount AS chequeamount
,p.Amount As PolicyAmount
,(c.Amount) - SUM(p.Amount) OVER (PARTITION BY c.ChequeID) AS Difference
FROM Cheque c
LEFT JOIN Policy AS p
ON p.ChequeId=c.ChequeId
GROUP BY chequeNumber, policyNumber,c.amount,p.Amount,c.ChequeID
这给了我两个行(下表)的差异,而不仅仅是映射的最后一个策略。
ChequeNumber PolicyNumber ChequeAmount PolicyAmount Difference
1 1 200 100 -100
1 2 200 200 -100
我正在使用SQL 2008 R2。
答案 0 :(得分:0)
由于您使用的是SQL Server 2008,因此对WINDOW函数的支持有限,因此您需要自联接:
WITH DATA AS
(
SELECT chequeNumber AS chequeNumber
,COALESCE(p.policyNumber, '') AS PolicyNumber
,c.amount AS chequeamount
,p.Amount As PolicyAmount
,P.MovingSum
FROM Cheque c
LEFT JOIN (SELECT P1.PolicyId
,P1.PolicyNumber
,P1.ChequeId
,P1.Amount
,P1.Amount + COALESCE(P2.Amount, 0) AS MovingSum
FROM Policy AS P1
LEFT JOIN Policy AS P2
ON P1.ChequeId = P2.ChequeId
AND P1.PolicyId > P2.PolicyId
AND P1.PolicyNumber > P2.PolicyNumber) AS p
ON p.ChequeId = c.ChequeId
GROUP BY chequeNumber, policyNumber, c.amount, p.Amount, c.ChequeID, p.MovingSum
)
SELECT chequeNumber
,PolicyNumber
,chequeamount
,PolicyAmount
,CASE WHEN MovingSum > PolicyAmount THEN MovingSum - chequeamount ELSE 0 END AS Difference
FROM DATA;
答案 1 :(得分:0)
如果我理解正确,你需要计算它们之间的差异 保单金额 - (支票金额 - 已分配给以前保单金额的金额) 考虑到分配是以policynumber顺序,这应该工作:
SELECT chequeNumber AS chequeNumber
,COALESCE(p.policyNumber, '') AS PolicyNumber
,c.amount AS chequeamount
,p.Amount As PolicyAmount
,p.amount -
CASE WHEN
(c.Amount - (SELECT SUM(p1.amount) FROM cheque c1 LEFT JOIN policy p1 ON p1.chequeid=c1.chequeid AND p1.policynumber < p.policynumber)) < 0 THEN 0
ELSE (c.Amount - (SELECT SUM(p1.amount) FROM cheque c1 LEFT JOIN policy p1 ON p1.chequeid=c1.chequeid AND p1.policynumber < p.policynumber)) END Difference
FROM Cheque c
LEFT JOIN Policy AS p
ON p.ChequeId=c.ChequeId
GROUP BY chequeNumber, policyNumber,c.amount,p.Amount,c.ChequeID