I have used the way you said. But some how when it has a name it adds an extra ' apostrophe which breaks the query. Can you please check this 
{%
if (QueryString.GetValue("tagname")!= null ) 
{
return "(DocumentID IN (SELECT DocumentID FROM CMS_DocumentTag WHERE TagID IN (SELECT TagID FROM CMS_Tag WHERE TagName = '" +  QueryString.GetValue("tagname").ToString() + "' AND TagGroupID = 3) ))";
}
 
if (QueryString.GetValue("categoryname")!= null )
{
return "(DocumentID IN ( SELECT DocumentID FROM CMS_DocumentCategory WHERE CategoryID IN (SELECT categoryid FROM CMS_Category WHERE categorydisplayname = '" + QueryString.GetValue("categoryname") + "'))"
}
%}This is the Query which comes in 
SELECT TOP 5 BlogPostTeaser, BlogPostSummary, BlogPostBody, BlogPostTitle, BlogPostDate, 
NodeAliasPath, DocumentURLPath, SiteName, NodeOwner, DocumentTags, DocumentTagGroupID, 
DocumentID, BlogAuthor, NodeXML, DocumentCulture, NodeID, NodeLinkedNodeID, ClassName, NodeLevel,
 NodeOrder, NodeParentID FROM View_CMS_Tree_Joined_Versions INNER JOIN CONTENT_BlogPost
  ON View_CMS_Tree_Joined_Versions.DocumentForeignKeyValue = CONTENT_BlogPost.[BlogPostID] WHERE 
  ((((NodeSiteID = 2) AND (DocumentCulture = N'en-US')) AND (NodeAliasPath LIKE N'/%')) AND 
  (('0' = 0 AND ''='') OR (DocumentID IN (SELECT DocumentID FROM CMS_DocumentTag WHERE TagID = 0 )) OR 
  (DocumentID IN (SELECT DocumentID FROM CMS_DocumentTag WHERE TagID IN (SELECT TagID FROM CMS_Tag WHERE TagName = ''Test'' AND TagGroupID = 0 ))))) AND 
  (ClassName = 'CMS.BlogPost') ORDER BY BlogPostdate DESC