我有一张表格,可以返回每个帐户,年/月期间和每家公司的所有余额和累计金额。 Please see image here
这是我的问题。有一些YearMonth条目,我根本没有交易,所以对于那些帐户我没有记录。 但由于我显示累计金额,因此我必须在所有YearMonth期间显示所有帐户。
我创建了一个单独的帐户表,其中我有所有帐户强制(通过左连接)第一个表来检索给定年/月的所有帐户,但它不起作用。
有人可以建议任何解决方法吗?有什么想法吗?
谢谢。
答案 0 :(得分:0)
对所有年份和月份的列表进行硬编码并保持与现有表格的连接:
with ym as(
select * from (values ('201401'), ('201402'), ('201403'), ('201404'), ('201405'), ('201406'), ('201407'), ('201408'), ('201409'), ('201410'), ('201411'), ('201412'),
('201501'), ('201502'), ('201503'), ('201504'), ('201505'), ('201506'), ('201507'), ('201508'), ('201509'), ('201510'), ('201511'), ('201512'),
('201601'), ('201602'), ('201603'), ('201604'), ('201605'), ('201606'), ('201607'), ('201608'), ('201609'), ('201610'), ('201611'), ('201612'),
('201701'), ('201702'), ('201703'), ('201704'), ('201705'), ('201706'), ('201707'), ('201708'), ('201709'), ('201710'), ('201711'), ('201712'),
('201801'), ('201802'), ('201803'), ('201804'), ('201805'), ('201806'), ('201807'), ('201808'), ('201809'), ('201810'), ('201811'), ('201812'),
('201901'), ('201902'), ('201903'), ('201904'), ('201905'), ('201906'), ('201907'), ('201908'), ('201909'), ('201910'), ('201911'), ('201912')) a(YearMonth))
select ym.YearMonth, at.AccountNumber, mt.*
from ym
cross join [Accounts Table] at
left join [My query of transactions with YearMonth and Accounts] mt on mt.YearMonth = ym.YearMonth and mt.AccuntNumber = mt.AccountNumber