Match Logic using Java and SQL