1
create temporary table sand_scipher_ds_db.public.Rf as (
  select PATIENTID, max(SVCDATE)-min(SVCDATE) as days from symphony_hvh_db.sym33.dx

  union all
  
  select PATIENTID, max(SVCDATE)-min(SVCDATE) as days from symphony_hvh_db.sym.dx
  group by PATIENTID
  having days>90
  limit 100
);
select * from sand_scipher_ds_db.public.Rf limit 100

error: SQL compilation error: [DX.PATIENTID] is not a valid group by expression

Luuk
  • 12,245
  • 5
  • 22
  • 33
User1011
  • 143
  • 1
  • 10
  • Which RDBMS are you using? Also: When using `LIMIT`, you should also add an `ORDER BY` to be sure to return the records that you expect. – Luuk Dec 07 '21 at 10:02
  • I'm using snowflake – User1011 Dec 07 '21 at 11:28
  • The problem seems to be the same as [Snowflake: "SQL compilation error:... is not a valid group by expression"](https://stackoverflow.com/questions/58984820/snowflake-sql-compilation-error-is-not-a-valid-group-by-expression), but, sorry, I do not see why you are having "PATIENTID is not a valid group by expression" – Luuk Dec 07 '21 at 11:54

1 Answers1

1

You need a group by on both sides of your UNION ALL as this is failing because you are using an aggregate function against sym33.dx without specifying a group by. Therefore, PATIENTID is not a valid group by expression in the first select.

create temporary table sand_scipher_ds_db.public.Rf as (
  select PATIENTID, max(SVCDATE)-min(SVCDATE) as days from symphony_hvh_db.sym33.dx
  group by PATIENTID
  having days>90

  union all
  
  select PATIENTID, max(SVCDATE)-min(SVCDATE) as days from symphony_hvh_db.sym.dx
  group by PATIENTID
  having days>90
  limit 100
);
select * from sand_scipher_ds_db.public.Rf limit 100

It's also possible that you wanted to union all and then do the group by. You'd need to do a sub-select like this:

create temporary table sand_scipher_ds_db.public.Rf as (
  select a.PATIENTID, max(a.SVCDATE)-min(a.SVCDATE) as days from
  ( 
    select PATIENTID, SVCDATE from symphony_hvh_db.sym33.dx
    union all
    select PATIENTID, SVCDATE from symphony_hvh_db.sym.dx
  ) a
  group by PATIENTID
  having days>90
  limit 100
);
select * from sand_scipher_ds_db.public.Rf limit 100
Mike Walton
  • 6,595
  • 2
  • 11
  • 22