简体   繁体   中英

MAX with UNION subquery does not produce desired results

I'm having a trouble with getting the max date from a UNION subquery. My code looks like this:

SELECT MX.LOCATION AS LOC, MAX(MX.TIMESTAMP) AS TIME
FROM

  (SELECT TAB1.LOCATION AS LOCATION, TAB2.TIMESTAMP AS TIMESTAMP
   FROM TABLE1 TAB1
   JOIN TABLE2 TAB2 ON TAB1.ID=TAB2.ID
   WHERE TAB2.COMPANY =3

   UNION

   SELECT TAB3.LOCATION AS LOCATION, TAB2.TIMESTAMP AS TIMESTAMP
   FROM TABLE3 TAB3
   WHERE TAB3.COMPANY = 3) MX

GROUP BY MX.LOCATION

Problem occurs when I have the same location in two queries joined by UNION. What I'm getting is MAX timestamp from the 1st query and the 2nd. What I want is simply MAX for each location - not both of them.

SAMPLE DATA. OUTPUT OF UNION STATEMENT. TABLE COLUMN ONLY INDICATES DATASET ROWS BELONG TO

LOCATION  TIMESTAMP        TABLE
855       2017-07-29 13:48 TAB1
856       2017-07-28 14:50 TAB1
855       2017-07-29 11:48 TAB2

RESULT
LOCATION  TIMESTAMP
855       2017-07-29 11:48
855       2017-07-29 13:48
856       2017-07-28 14:50

Problem solved. Some locations had spaces in them. I used TRIM function to solve it.

Query can be written following

with allTableInformation as (

SELECT tb1.location, tb1.time
from table1 tb1

union
select tb2.location, tb2.time
from table2 tb2

union
select tb3.location, tb3.time
from table3 tb3
) 
select distinct on (location) location, time from allTableInformation 
order by location, time desc

You can try query in demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM