我有两张表F和表D.
表F提供了有关账户金融交易的详细信息(付款,收费,利息......) 表D显示了拖欠状态(如果用户未付款)。它显示了不同的状态代码。 0,1,2,11(意思是不同的东西)
我的表格结构如下:
Table F
============
-------------------------------------------
|AccountId|TypeCode |BusinessDate|TransAmt|
-------------------------------------------
|12345 | PYMT |2016-06-22 | 10.54|
-------------------------------------------
|12345 | TOLL |2016-06-15 | 04.00|
-------------------------------------------
|12345 | INTR |2016-05-26 | 01.66|
-------------------------------------------
|12345 | TOLL |2016-04-10 | 04.00|
-------------------------------------------
Table D
==========
-----------------------------------------------
|AccountId|FromID|ToID|CreatedDate |
-----------------------------------------------
|12345 | 0| 2|2016-12-25 00:12:44.453|
-----------------------------------------------
|12345 | 2| 1|2017-04-02 07:16:46.770|
-----------------------------------------------
|12345 | 1| 11|2017-07-12 16:16:36.747|
-----------------------------------------------
我正在尝试运行代码以查找帐户进入状态码11(ToID)后帐户上所有付款的总和
我的代码:
SELECT F.AccounttID
,ISNULL(SUM(TransAmt), 0) Payments
FROM F INNER JOIN D ON F.AccounttID = D.AccountId
WHERE AccountId = 12345
AND TypeCode = 'PYMT'
AND F.BusinessDate >= D.CreatedDate
AND ToID = 11
--AND F.BusinessDate >= (SELECT CreatedDate FROM D WHERE F.AccounttID = D.AccountId AND ToID = 11)
GROUP BY F.AccountID, F.TypeCode
我得到的结果是:
--------------------
|AccountID|Payments|
--------------------
| | |
--------------------
我想要的结果是:
--------------------
|AccountID|Payments|
--------------------
| 12345| 0.00|
--------------------
答案 0 :(得分:1)
删除GROUP BY
:
SELECT MAX(F.AccounttID) as AccounttID,
COALESCE(SUM(TransAmt), 0) Payments
FROM F INNER JOIN
D
ON F.AccounttID = D.AccountId
WHERE AccountId = 12345 AND
TypeCode = 'PYMT' AND
F.BusinessDate >= D.CreatedDate AND
ToID = 11
--AND F.BusinessDate >= (SELECT CreatedDate FROM D WHERE F.AccounttID = D.AccountId AND ToID = 11)
这似乎违反直觉。但是,即使所有行都被过滤掉,也确保没有GROUP BY
的聚合查询只返回一行。使用GROUP BY
,聚合查询每组返回一行。如果过滤掉所有行,则不返回任何行。
答案 1 :(得分:1)
您的问题是您的where
条件没有匹配结果。我认为你实际上是想使用conditional aggregation
。我还使用了outer join
,以防无法匹配:
SELECT F.AccounttID
,SUM(CASE WHEN F.BusinessDate >= D.CreatedDate THEN F.TransAmt ELSE 0 END) Payments
FROM F
LEFT JOIN D ON F.AccounttID = D.AccountId AND D.ToId = 11
WHERE F.AccountId = 12345
AND F.TypeCode = 'PYMT'
GROUP BY F.AccountID