Extract common sql building logic from pivot cmd
Update Hierrchicl query to use common sql builder