SQL Server find the values of the latest dates

63lcw9qa  于 2023-05-05  发布在  其他
关注(0)|答案(4)|浏览(181)

I have these two datasets
t5 and t6

I want to find the tax_id with the latest date

So I have used UNION instead of join

Select * from (
Select s_id, tax_id, date_of,
row_number() over(partition by s_id order by date_of) row_num
FROM
(Select * from t5
UNION
Select * from t6) s1) s2

There is a value 2 with only have the same txn_date
I also want to take that as the latest one

EDIT : Thanks for your help
I am using SQL Server
I want the output as below.

oxiaedzo

oxiaedzo1#

Generate dataset using UNION ALL then apply row_number() on it to generate row numbers by descendant order and pick the ones with rn = 1 :

with cte as (
  select s_id, tax_id, date_of, row_number() over (partition by s_id order by date_of desc ) as rn
  from (
    select * 
    from t5
    union all
    select * 
    from t6
  ) as s
)
select s_id, tax_id, date_of
from cte
where rn = 1
vecaoik1

vecaoik12#

Use rownum = 1 for getting one data from list in Oracle SQL

SELECT *
  FROM (SELECT *
  FROM t5
 UNION ALL
SELECT *
  FROM t6) sq
 WHERE rownum = 1
ORDER BY date_of desc
bksxznpy

bksxznpy3#

Select everything from two tables with UNION ALL and then choose the latest date by LIMIT 1

SELECT * FROM t5
UNION
(SELECT * FROM t6)
ORDER BY date_of DESC
LIMIT 1

It would work for PostgreSQL, but I guess, for other DBMS it might work too.

jfgube3f

jfgube3f4#

To find the latest date for each tax_id you could use the GROUP BY clause with MAX aggregate function.

For this query to work in the majority of DBMS, date_of has to be defined as a datetime type.

SELECT tax_id, MAX(date_of) AS max_date_of
FROM (SELECT tax_id, date_of FROM t5 UNION SELECT tax_id, date_of FROM t6) t
GROUP BY tax_id

相关问题