Please provide sample tables, data, and expected output. We can't do much for you without that as a starting point. Also, I don't understand your question about query or procedure...
Best,
Kevin G. Boles
SQL Server Consultant
SQL MVP 2007-2012
TheSQLGuru on googles mail service