A 40-unit apartment building located less than a half mile from the beach in Carlsbad has been sold for $20.9 million.