Move code from template file to custom module
I think you should go through the module developer guide.

You can use hook_preprocess_HOOK() in your template.php. So if your code was placed in the node template, the hook will be themename_preprocess_node($vars) and then you can check for a particular node type and create a variable like $vars['custom_variable'] = 'the query stuff'; and this variable will be available in your template.