Back wheel slipping on loose ground
There's a few reasons you could have a rear wheel sliding around. I'll go through them briefly:


Traction: This sums up several different issues, but basically it means the rear tire is no longer gripping the surface you're riding on.


Tires: Moving a certain speed will cause the tire to break loose, no matter how much grip it has. The tire profile also has a strong impact on how it will react. Some tires have large knobs to assist with cornering, or small knobs to reduce rolling resistance. This goes for center tread as well, with some tires having an aggressive pattern to increase traction. Of course, smaller details like tire material can influence this as well (durometer of the rubber, mixed tread compounds, etc.).
Surface: You know a car can slide around in the snow? The same can happen to a bike and not just on ice/snow. Mud, water, leaves, and sand can all cause the same thing. Tire choice can help to reduce the effects of different surface qualities, but eventually you're going to have one surface that acts differently than another.
Weight: Push down on something enough and it becomes hard to move, even if the bottom is slippery. Similar theory can be applied to biking. This is most noticeable when climbing hills. As you shift your weight forward in the saddle (or further when standing) you take weight off the rear wheel which reduces the ability of the tire to remain in contact with the ground.

Spin-out: If your getting the occasional time when the rear wheel seems to just spin in place on the ground you might be putting down too much power and exceeding the grip of the tires. This can happen on loose climbs, flats, or elsewhere. Try lowering the gear to one you can spin in (but not too low).


After all that, there's also the practice of skidding/drifting by purposefully locking up the rear wheel and letting it break free. Sometimes it looks cool, sometimes it allows you to go faster around a corner, but doing it consistently requires you to know how your bike and tires will handle at different speed and varying terrain.