select docid, max(tot) from(
select f.docid, sum(f.count*q.count) as tot
from frequency f join
(SELECT * FROM frequency
UNION
SELECT 'q' as docid, 'washington' as term, 1 as count 
UNION
SELECT 'q' as docid, 'taxes' as term, 1 as count
UNION 
SELECT 'q' as docid, 'treasury' as term, 1 as count)q on f.term=q.term
where q.docid='q'
group by f.docid
)
;