Cleanup for #545 moved complex sql into view

need to run view ddl in scema.sql