1 Chronicles 21:16,17 (KJV)
16 And David lifted up his eyes, and saw the angel of the Lord stand between the earth and the heaven, having a drawn sword in his hand stretched out over Jerusalem. Then David and the elders of Israel, who were clothed in sackcloth, fell upon their faces.
17 And David said unto God, Is it not I that commanded the people to be numbered? even I it is that have sinned and done evil indeed; but as for these sheep, what have they done? let thine hand, I pray thee, O Lord my God, be on me, and on my father’s house; but not on thy people, that they should be plagued.
What We Think Is Good, God May Think Otherwise
What David had Joab do, Joab knew in the back of his mind that it was wrong and God would not be happy with it.