1

How would I go about combining many query results, all from different tables, into one resulting table?

SELECT LEAST( (HSDIPLOMA + BACHELORDEGREE) / AVG(HSDIPLOMA + BACHELORDEGREE) OVER (),
              1
            ) as res
FROM EDUCATIONPROFILE
ORDER BY cid ASC
SELECT LEAST( (EMPLOYED -  UNEMPLOYED) / AVG(EMPLOYED - UNEMPLOYED) OVER (),
              1
            ) as res
FROM ECONOMICPROFILE
ORDER BY cid ASC
SELECT ((MAXTEMP + MINTEMP)/ 2)/ (SELECT MAX((MAXTEMP + MINTEMP)/ 2) FROM CLIMATEPROFILE) FROM CLIMATEPROFILE ORDER BY cid ASC
SELECT (crimecount) / (SELECT MAX(CRIMECOUNT)  FROM CRIMECOUNTS) FROM CRIMECOUNTS ORDER BY cid ASC

The goal being one query result (table) with different columns each having one of the respective queries result.

1 Answer 1

2

Since all appear to have cid, simply JOIN each resultset:

SELECT educ.cid, educ.educ_res, econ.econ_res, clim.climate_res, crime.crime_res
FROM
  (SELECT LEAST((HSDIPLOMA + BACHELORDEGREE) / 
                 AVG(HSDIPLOMA + BACHELORDEGREE) OVER (), 1) AS educ_res
   FROM EDUCATIONPROFILE
  ) educ

INNER JOIN
  (SELECT LEAST((EMPLOYED -  UNEMPLOYED) / 
                AVG(EMPLOYED - UNEMPLOYED) OVER (), 1) AS econ_res
   FROM ECONOMICPROFILE
  ) econ
ON educ.cid = econ.cid

INNER JOIN 
  (SELECT ((MAXTEMP + MINTEMP)/ 2)/ 
           (SELECT MAX((MAXTEMP + MINTEMP)/ 2) FROM CLIMATEPROFILE) AS climate_res
   FROM CLIMATEPROFILE
  ) clim
ON clim.cid = educ.cid

INNER JOIN
  (SELECT (crimecount) / (SELECT MAX(CRIMECOUNT)  FROM CRIMECOUNTS) AS crime_res
   FROM CRIMECOUNTS
  ) crime
ON crime.cid = educ.cid

ORDER BY educ.cid

Alternatively with CTEs:

WITH educ AS
  (SELECT LEAST((HSDIPLOMA + BACHELORDEGREE) / 
                 AVG(HSDIPLOMA + BACHELORDEGREE) OVER (), 1) AS educ_res
   FROM EDUCATIONPROFILE
  ), 
     econ AS 
  (SELECT LEAST((EMPLOYED -  UNEMPLOYED) / 
                AVG(EMPLOYED - UNEMPLOYED) OVER (), 1) AS econ_res
   FROM ECONOMICPROFILE
  ), 
     clim AS
  (SELECT ((MAXTEMP + MINTEMP)/ 2)/ 
           (SELECT MAX((MAXTEMP + MINTEMP)/ 2) FROM CLIMATEPROFILE) AS climate_res
   FROM CLIMATEPROFILE
  ), 
     crime AS
  (SELECT (crimecount) / (SELECT MAX(CRIMECOUNT)  FROM CRIMECOUNTS) AS crime_res
   FROM CRIMECOUNTS
  ) 

SELECT educ.cid, educ.educ_res, econ.econ_res, clim.climate_res, crime.crime_res
FROM educ
INNER JOIN econ 
    ON educ.cid = econ.cid
INNER JOIN clim
    ON clim.cid = educ.cid
INNER JOIN crim
    ON crime.cid = educ.cid
ORDER BY educ.cid
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.