Thanks for your solution . It gives me required result. I want to use this solution for different tables. So I have 2 way for implementing this solution
To create prepared Statement for this query and using it
Creating stored procedure for it .and called it fro java code