The account of 2 Samuel 24 may be explained by referencing Exodus 30:12
"When you take a census of the Israelites to count them, each one must pay
the LORD a ransom for his life at the time he is counted. Then no plague
will come on them when you number them." (NIV)
Evidently David neglected this little detail in the process of counting
the people.