To start, I don't think it's possible to know for sure what any animal behavior means or why it takes place. All we can do is study different species, collect data, and come to sensible conclusions. In the case of why dogs wag their tails, I'm not sure much study needs to take place. It generally means, like you said, they're either happy, excited, or both. But that wasn't actually your question. Yes, when a dog is happy, it wags its tail. But why has the dog chosen the tail to wag as opposed to nodding its head up and down? Or giving you a paw to shake?
Most of what dogs do is to communicate with humans, other animals, or other dogs. They use the position of their ears to say one thing and a facial expression to say something else. They howl, bark, exhibit certain postures, and wag their tails to say other things. In general, when a puppy reaches the age of around eight weeks, you'll see it begin to wag its tail. As puppies become more comfortable with their interactions between people and other dogs, they'll use their tails to communicate their moods. Plenty of people who specialize in animal behavior have determined that tail wagging is inherent in a dog's existence, meaning it's passed down from generation to generation genetically. Wild dog species, including wolves, use a variety of expressions to communicate with friends and enemies alike. They wag tails, bark, and growl. Most of the time, it's the happiness that instigates the tail wagging. It means the dog is happy to see you and that it's friendly. Be careful though because not all tail movement means a dog is friendly. Have you ever seen a dog hold its tail straight up and move only the tip? Beware of that one. That's a warning to stay away. A more docile or submissive dog will generally hold its tail down and wag it stiffly. Usually this type of dog will also hang its head and lower its body - and perhaps crouch as well.
It's important to learn about how dogs choose to communicate with humans and other dogs. If you're ever in doubt, as the owner about the dog's personality if the dog is a stranger and always ask permission to pet a dog.