我在从UNION子查询获取最大日期时遇到麻烦。我的代码如下:
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
在两个由UNION连接的查询中具有相同位置时,会出现问题。 我得到的是来自第一个查询和第二个查询的MAX时间戳。我想要的只是每个位置的MAX-而不是两个。
样本数据。联盟声明的输出。表列仅表示数据集行不正确
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
答案 0 :(得分:0)
问题解决了。一些位置中有空格。我用TRIM函数来解决它。
答案 1 :(得分:0)
查询可以写在下面
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
您可以尝试在demo
中查询