Genesis chapter 39 and 2 Samuel chapter 11 show similar situations, with different actions and different results. In Genesis 39, Joseph's luck has changed for the better. Betrayed by his brothers and sold into slavery, he ends up at Potiphar's house. Potiphar promotes Joseph and gives him control over practically everything. He finds himself constantly tempted by Potiphar's wife, but manages to resist, because he knows to give in is wrong, and would displease the Lord. Now the Bible doesn't mention whether he found her attractive, but the point is the opportunity was there. So, Joseph continues to resist, even leaving his clothing behind at one point, intent only on running as far as he can from sin and temptation. His reward? Jail. He's falsely accused by Potiphar's wife, and Potiphar has him thrown in prison.
On the other hand, 2 Samuel 11 shows David doing just the opposite. Instead of running from temptation, he gives in. He sees a beautiful woman bathing on a nearby roof. Instead of looking away, moving away, he decides he wants her. He lets nothing stand in his way, going so far as to murder Bathsheba's husband in order to hide his impropriety. And he ends up with the girl and a baby on the way. But the thing that David had done displeased the LORD. (2 Samuel 11:27) On the surface, it would seem that David got the better end of the deal, and that would be true if their stories ended there. But they don't.
Joseph ends up second in command in all of Egypt, and David ends up losing his son, and facing war through the rest of his reign. This has been weighing heavily on my mind because I recently had to deal with a similar situation, and, though it may sometimes seem like you get punished for doing the right thing, in the end you will be rewarded. The wages of sin is death. (Rom 6:23) David learned that the hard way.