Ah... it then turned into one of those times where you've solved the piece of the puzzle and everything just starts dropping into place. "Ah ha! I pulled that code into a separate function because I'd used nearly the same code twice, and that's just good practice. Now I see if I just add one more parameter to that function, and recode it a bit here it becomes general enough that I can reuse it to do that job everywhere".
OK so "recode it a bit here" meant turning a simple SQL statement into something that dynamically generates the SQL depending on the parameters, which is somewhat unpleasant, but still the best solution I could think of as it minimised code replication.
It's been a while since I last got the puzzle-solving programming buzz, I miss it. (Though not enough to want to go back to programming for a living, I'm too sloppy to be able to consistently write good code.)