简体   繁体   中英

SQL - need a query for the last_date for each user, max_date, min_date

The original table looks like:

id   date        name
----------------------
11   01-2021     'aaa'
11   03-2020     'bbb'
11   01-2019     'ccc'
11   12-2017     'ddd'
12   02-2011     'kkk'
12   05-2015     'lll'
12   12-2020     'mmm'

the expected output:

id.   min_date.  max_date   name
---------------------------------
11    12-2017    01-2021    'aaa'
12    02-2011    12-2020    'mmm'

I need to have, min, max dates and the name that corresponds to the max_date. I know a way to get min, max dates and separately how to get the date corresponding to the max_date (using ROW_NUMBER() OVER(PARTITION BY...)), but cannot figure out how to combine both together.

One option is to use ROW_NUMBER along with pivoting logic to select the name corresponding the max date per each id :

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY date DESC) rn
    FROM yourTable
)

SELECT
    id,
    MIN(date) AS min_date,
    MAX(date) AS max_date,
    MAX(CASE WHEN rn = 1 THEN name END) AS name
FROM cte
GROUP BY
    id;

下面演示链接的屏幕截图

Demo

Note that your current date column appears to be text. Don't store your dates as text, instead use a proper date column.

This below query should work

SELECT *
FROM tbl1 t1
INNER JOIN
  (SELECT id,
          min(date) AS min_date,
          max(date) AS max_date
   FROM tbl1
   GROUP BY id) t2 ON t1.date = t2.max_date

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