This incident in King David's life is recorded in two places, 2 Samuel 24 and 1 Chronicles 21. There are differences in the accounts, so let's start with the one that seems more clear: "Now Satan stood up against Israel, and moved David to number Israel" (1 Chronicles 21:1 1 Chronicles 21:1And Satan stood up against Israel, and provoked David to number Israel.
American King James Version×). So Satan tempted David, and David didn't resist strongly enough to overcome the urge to disobey God.
In 2 Samuel 24:1 2 Samuel 24:1And again the anger of the LORD was kindled against Israel, and he moved David against them to say, Go, number Israel and Judah.
American King James Version×it says: "Again the anger of the Lord was aroused against Israel, and He moved David against them to say, 'Go, number Israel and Judah.'" A commentary, Barnes' Notes, suggests that the first sentence is actually the title for the section that follows: "And again the anger of the Lord was kindled against Israel." Then the text would begin with, "He moved David against them."
Note that when challenged by the military commander, Joab, about taking a census, David didn't say God told him to take it. David just told Joab to follow orders. Verse 4 says "the king's word prevailed," not that God's word prevailed. So we could say God allowed Satan to tempt David to do what he and the people naturally wanted to do.
So what was wrong with taking a census in this case? The Wycliffe Bible Commentary explains that there were two reasons for taking a census in those days: (1) to assess a tax on the population; (2) to prepare to conscript an army. God had blessed David with abundance and had given Israel peace from its enemies. So it seems taking a census demonstrated a lapse in David's faith, for he was looking to the physical evidence of his national strength, instead of depending upon God to be the nation's shield. Perhaps David was planning a military expansion campaign that God had not sanctioned.
Whatever the case, David realized he had "sinned greatly" (2 Samuel 24:10 2 Samuel 24:10And David's heart smote him after that he had numbered the people. And David said to the LORD, I have sinned greatly in that I have done: and now, I beseech you, O LORD, take away the iniquity of your servant; for I have done very foolishly.
American King James Version×), and we know from verse 1 that Israel had sinned and aroused God's anger. So although numbering the people is not always a sin (Numbers 1 and 26), it is clear that this time it was.
For more understanding, please read our GN article Profiles of Faith: David - A Man After God's Own Heart.