...
CREATE TABLE diagnosishypertension_first SELECT STUDY_ID, DIAGNOSIS_DATE AS DIAGNOSIS_DATE_FIRST, ENCOUNTER_ID FROM diagnosishypertension a WHERE DIAGNOSIS_DATE = (SELECT MIN(DIAGNOSIS_DATE) FROM diagnosishypertension b WHERE b.STUDY_ID=a.STUDY_ID)
The solution is to read into MATLAB. However, we run out of java heap memory, so we need to 1) increase the meomery, and 2) set the db preferences to read in batches.
Now we get a pretty good reduction - 48+hours to 1 minute!