In Animorphs, after years of unimaginable pressure and War Is Hell torment, the kids become the greatest heroes in the history of humanity. However, only Marco, Cassie and Ax get to profit from it - Jake's clinically depressed due to his actions aboard the Pool ship, and Tobias struggles to live a solitary existence in the woods.
In Catherine and Her Fate, Catherine, given the choice between happiness in youth and old age, picked old age. She then finds that her Fate will see to it that she must have a truly abject life until then, and soldiers on.
Ciaphas Cain series can fit into this trope. Cain sometimes gets really lucky, but we must recognize luck usually works as many times against him as in his favour, he still has to fight and figure out a way to save his life most of the time, but in the end, when he has managed to save the day (and usually the entire sector), he and his friends can go to a nice place to enjoy some amasec and tanna while tasting some delicacies. He managed to earn his retirement, which is to say something, considering the rate of casualties in the Imperial Guard, and after some decades he saved the world where he was (again), ensuring himself (again) his good retirement.
K.A. Applegate's Everworld series. It's set in a world where all the gods and creatures from mythology exist, and as anyone who's read their mythology can tell you, that means horrible deaths and fates worse than death abound. And that's before Everworld is invaded by psychotic, heavily armed Neo-Nazis and an alien horde with their own god that eats other gods. For most of the series, the four teenagers who make up the main cast are barely able to keep themselves from killing each other, let alone staying alive, yet in the last book they actually manage to forge an alliance among the squabbling gods, start an industrial revolution in Everworld, and (while the series ends before the aforementioned Nazis and aliens can be defeated) the prospects for obtaining something close to peace are actually looking up.
This is one of the reasons a lot of readers find Terry Goodkind so irritating. Every single book of the Sword of Truth series makes it seem like the heroes have earned their happy ending, but the next book always reveals yet another previously-unexplained plot device that the author can use to torture them for another 600+ pages. The reason he does this is to avoid cliffhanger endings, but depending on your mileage, the cure might actually be worse than the disease.
Lloyd Alexander's Chronicles of Prydain: Taran becomes the King of Prydain and marries the girl of his dreams, but only after losing several friends (and many others leaving forever) and having his idealistic image of a 'hero' shattered. Not only that, all the magic in the world is disappearing, leaving him to rule a much-more-mundane kingdom. Even then his ending isn't that happy, but the afterword seems to indicate that he at least accepts it, as his fading into legend would indicate an ending that may not necessarily be happy but at least positive.
Surprisingly, especially for an H.P. Lovecraft story, "The Dream Quest of Unknown Kadath" has this. The protagonist dispels Nyarlathotep's deception and narrowly avoids his doom, before waking up in the beautiful and architecturally extraordinary city of Boston, USA. Nyarlathotep then admits defeat, making this probably the happiest ending to any story in the Cthulu Mythos.
The Blade of the Flame: The evil wereshark plot is foiled and Makala is no longer possessed, but Asenka is dead, Makala is still a vampire, and the two male leads and their Love Interests are forced to go their separate ways.
Robin Hobb's later fantasy trilogiesThe Liveship Traders and The Tawny Man go through an incredibly dark journey and emerge to a more or less happy ending.
The Gormenghast series practically defines this trope. Titus goes through Hell and back, losing almost everybody he cares about to take down Steerpike, but in the end, he has a world to explore, a world to win.
World War Z chronicles the entirety of a Zombie Apocalypse, from the dark portents of danger, the manic reaction of humanity, the soulless survival techniques that many resorted to, and the horrors of the living dead. Despite this, it manages to have an undercurrent of hope that gets stronger, running side by side with the cynicism and blackness. After all, Humanity did win the war, in the end.
On a more individual level, Gara/Lara/Kirney's plotline through the Wraith Squadron books. She goes from an Imperial agent whose loyalty isn't deserved by those she serves, to a potential mole in Wraith Squadron, to a loyal member of said squadron who is in a relationship with a man, Myn, whose squadron she got destroyed when she was an Imperial. It probably comes as no surprise that her identity as a former Imperial Agent is revealed, and Myn ends up trying to kill her. Then she ends up back on an Imperial vessel, posing as a loyal soldier while actually sabotaging the ship for the benefit of the Republic. Then she's forced to fake her own death to avoid execution for treason from either side of the board. And all throughout this she suffers from Sanity Slippage due to having a Double Consciousness brought on by the stress of her Intelligence background. A (much) later book, Mercy Kill reveals that Myn found her, they got married, and had kids, but she went through a lot to be able to get there.
Both Sabriel and Touchstone in Sabriel are put through the metaphysical wringer. By the end, they've both lost their entire families and a lot of their friends to Kerrigor's undead minions. In the end, though Sabriel is saved from death by relatives in the beyond telling her it's not her time, and she and Touchstone are well on their way to a happily ever after. They even managed to save Mogget.
Stephen R. Donaldson's books are invariably like this.
Compared to some of John Brunner's other works (particularly The Sheep Look Up), The Shockwave Rider might have an ending that qualifies. "Well— how did you vote?"
Averted, Subverted, and Justified at the same time in Stephen King's The Dark Tower series. After a journeying for untold years to reach the Dark Tower (and consequently losing the greater number of his friends, lovers, and followers along the way) Roland FINALLY reaches the Dark Tower. However, upon reaching it he finds out that his existence is a cycle; he has made the journey to the tower an unknown number of times before this one. He is made to repeat his journey again and again until he finally learns his lesson (which is up to the reader to decide). He is, literally, sent back to the beginning of the series with no memory of what just happened. The trope is potentially played straight, however, by the fact that Roland may well be able to FINALLY complete his quest this time round.
Harry Potter goes through hell and loses several friends along the way, but in the end, he is able to defeat Voldemort through The Power of Love.
Mistborn — both the first and third books, actually. The second is more of a Downer Ending, since the Big Bad just escaped its imprisonment thanks to the heroine.
Melina Marchetta's spectacular On the Jellicoe Road (just Jellicoe Road in the US and UK) is an example of Earn Your Bittersweet Ending. Just about everybody who survives to the end has lost at least one loved one (often more), and the ending is still incredibly sad and unbelievably heartwarming.
Jane Eyre: "Reader, I married him." Jane Eyre had to struggle a lot before she could marry her one true love and enjoy a happy family life with him.
Honor Harrington really has to do this in one case especially. Over the course of "In Enemy Hands" and "Echoes of Honor" she is forced to surrender a ship captained by one of her oldest friends, with that friends' birthday party on board, captured, put into the hands of someone who is basically Himmler without the intelligence to not believe the propaganda, has her empathic and emotion - sharing treecat permanently crippled (found out later - he can no longer speak to other treecats), has her artificial eye and half her face electrocuted, is sentenced to death, sees her sworn retainers die in the (barely) successful escape attempt, loses an arm, lands on a prison planet, takes over said prison planet, builds a navy from all the ships stopping by at the prison planet, steals transports for all the people on the prison planet, and finally arrives back in the nearest friendly system to discover everyone thought her dead - and they'd held the funeral, and named ships after her, and she had a brother and sister that were planned to inherit her title. And somehow the whole thing is worthwhile in the simple sentence: "She was taking them home, and they were taking her home, and that was all in the universe that mattered." Yes, all that happens in between her leaving on an escort mission and getting home again.
The only person in the entire Silmarillion who gets an actual Happy Ending with no strings attached might be Tuor, who gets to sail to Valinor with his wife Idril, and becomes an honorary Elf by the grace of Il˙vatar.
The Choose Your Own Adventure series could give this trope a whole new meaning. As it stands now, you do have to go through a lot to get to even the good endings.
The Candy Shop War is surprisingly dark for a kid's book, and features, among other things, a Jerk Ass witch-hunter, a Bad Future, a ten-year-old getting trapped in an And I Must Scream scenario, and enough Body Horror for five books. However, it ends with all the kids back to normal, everyone friends, good changes on the horizon, and the Big Bad herself rendered harmless as a friendly little girl.
In Brandon Mull's other series, Fablehaven, this trope also occurs. The books get worse, and worse, and worse, and worse, culminating in the fifth book where, despite all their efforts otherwise, the demon prison opens and thousands of demons are released into the world. However, thanks to a Batman Gambit by the Fairy Queen, a lot of powerful allies, and some well-placed magic, the demons are reimprisoned, this time for a much, much longer era, the good guys win, and the ending is completely and utterly happy.
Blade of Tyshalle, to a degree that can neither be safely summarized without spoiling everything, nor summarized well in a manner that does the novel justice.
In the second Empire from the Ashes book, humanity suffers heavy losses against the genocidal Achuultani invaders, destroying the entire wave at the cost of many heroic sacrifices galore, the destruction of most of the military—including Colin's big damn reinforcements—and a death toll on Earth exceeding 500 million people.
Quantum Gravity: by the end of the fourth book, Lila has been tortured by elves, lost her trust in Sarasilien, the humans she worked with, and generally finds that it's going to be hard to grow up. She also literally goes through hell. Zal goes through hell, and then things get worse. But by the end, they're together, and Lila has figured out how to Be Herself. It's...less sappy in context.
In Vampire Academy, Rose finally gets her happy ending after one of her closest friends dying, nearly going insane, the love of her life being turned Strigoi and gets eventually turned back after Rose nearly killing him twice, being tortured both through the bond with her best friend and actually tortured, getting accused of assassinating a monarch and nearly executed before she finds out that one of the people she trusts, likes and admires was the killer and set it all up on her.
Maurice by E.M. Forster ends on this note. This was the reason why the book was not published until 51 years after it was written.
The cast in Dragons in Our Midst go through hell and back for their happy ending. And no, that's not speaking metaphorically, a few of them literally go through hell.
The Acts of Caine: what could count as a Downer Ending in another work is a rather happy ending in this book, compared to the hell the characters have been through.
In the Xanth this is pretty much the entire schtick behind Good Magician Humphery's missions: Successfully completing a Humphery-given task pretty much guarantees you (and those who helped you) a Happily Ever After. And most who get stuck with the year's service as payment for his answers end up better off for the experience. It's implied that many of Xanth's citizens know this for a fact and that's why so many are willing to give up a year's freedom (at a minimum) to petition Humphery.
Question Quest was originally about Lacuna trying for the trope; only thing is, Humphrey had been missing for a little over a decade (since the start of the 2nd Xanth series, Vale of the Vole), so with a little help from Grey (Humphrey's protegÚ), she tracks him down. Turns out he's been playing a waiting game with the Demon X(A/N)th in a quest to earn his happy ending. They help each other out to earn their respective endings.
Les MisÚrables: After 2000 pages leaning very, very hard to the cynical side, Valjean dies redeemed in his own eyes and Marius's, confident that he's kept his promises to Fantine and Bishop Myriel, and confident that his beloved Cosette will be happy.
John Taylor and Suzie Shooter from Simon R. Green's Nightside series. Though given how things work in the Nightside in general, and relating to John and Suzie both together and individually, bittersweet is almost more than they or pretty much everyone in the series would expect/hope for. Though in the Nightside, Bittersweet IS happy when you put things in perspective. Of course there's still one final book left to finish the series, so it's possible they might not even get that.
All of Ayn Rand's fiction, except for We The Living. Howard Roark gets his skyscraper, recognition of his artistic genius, and the girl in The Fountainhead; John Galt gets America, and the girl, and the heroes are setting out to rebuild a second golden age in Atlas Shrugged; and Equality 7-2521 escapes, gets the girl, and sets out to rebuild the world in Anthem.
The two characters who get the happiest endings in the first duology of the Arcia Chronicles are Shander Gardani, the Stoic Woobie who performs several Last Stands and is magically tortured for months by the Big Bad, and Princess Ilana, whose ambitions lead her to become the Big Bad's personal plaything and to lose everyone she loves. The two end up surprisingly Happily Married and found a dynasty that endures uncorrupted for many centuries.
Matteo in Someone Else's War has lost his home, his entire family, most of his classmates, one of his best friends, and by all accounts, his innocence. But thanks to some craftiness and cooperation from his friends (whom he never would have had had he spent the entire novel as cold and judgmental as he was toward the beginning), he manages to dismantle the world's largest army and send the Child Soldiers home.
Tony Wayland in the last two books of Julian May's The Saga of Pliocene Exile.
In Sing You Home, Zoe and Vanessa fight in court with Zoe's born-again ex-husband Max, for their frozen embryos from their IVF treatment. Zoe and Vanessa want to have a family, and Max wants to give the embryos to his brother. Meanwhile, Max is in love with his brother's wife Liddy, and decides to give up the embryos because he doesn't want to see them happily raising his kids. In the end, they have a healthy girl, and Max gets Liddy.
This is how most Redwall books turn out. They're all happy endings but a lot of friends are lost, and it's never easy.
Trapped on Draconica: Team Good goes through a lot of hardship, a lot of pain, and a lot of suffering. Each one of them had a moment where they would have given up if not for the encouragement of the group. They all earn a happing ending.
Surely, the gods were merciful and loving. Surely they smiled upon this union, and he and his wives would live happily ever after.
At the end of The Wheel of Time books, millions are dead, many hundreds of thousands in the Last Battle alone, but they've defeated or dealt with the all of the Forsaken, crushed the army of Shadowspawn, Darkfriends and Dreadlords, and Re-sealed the Dark One. They've lost a lot of people on the way, but they have an Age of prosperiety awaiting them.
Nowhere is this more exemplified than with Rand, who after an absurd amount of It Sucks to Be the Chosen One, he gets to walk away in a new body free of pain or maiming, mostly anonymous, free of the responsibility that was constantly wearing away at his sanity, with new Reality Warper powers at the cost of his old abilities, and begins Walking the Earth.
The title character of Horatio Hornblower. From midshipman to admiral, he risks death daily, witnesses men die in horrible ways, loses a ship, loses several good officers, his first two children die of smallpox, he gets typhus in Russia, and his career is put at risk many times. Most of all, his "accursed unhappy temperament" prevents him from ever enjoying his many accomplishments because he'll always figure out a way to think of himself as a failure. But in the short story "The Last Encounter," Hornblower is retired, long since Happily Married to Lady Barbara, and finally happy and content for possibly the first time ever.
Swedish writer Simona Ahrnstedt does this in her debut novel Íverenskommelser. The poor female lead, Beatrice, has to suffer five years of abuse from her tyrannical uncle. And then he bullies his young niece into a marriage with a man, who's like forty years older than her and treats women like they're dirt under his shoes. So yeah, Beatrice is thrown into the mercy of another creep, who manages to brutally rape and batter her before he suddenly dies! Let's just hope that it was a really painful death... The story ends with Beatrice finally getting married to Seth, her love interest. But as they needed twenty months of suffering to get there, the happy ending sure was overdue...