I have the following data which has two columns journal
& published_year
CREATE TABLE journals (
journal VARCHAR(255) NOT NULL,
published_year INT NOT NULL
);
INSERT INTO journals (journal, published_year) VALUES
('Journal A', 2022),
('Journal B', 2017),
('Journal A', 2021),
('Journal C', 2018),
('Journal A', 2020),
('Journal C', 2017),
('Journal A', 2019),
('Journal B', 2016),
('Journal D', 2021);
I want the result data like the following
+-----------+----------------+
| journal | Last 2 Year |
+-----------+----------------+
| Journal A | 2022,2021,2020 |
| Journal B | 2017,2016 |
| Journal C | 2018,2017 |
| Journal D | 2021 |
+-----------+----------------+
3
Answers
Use the
GROUP_CONCAT
function to concatenate the last 2 years for each journal anda separated by commas.db<>fiddle output
Group concatenate by year and set a condition for two years group by journal and it’s done.
You can use exact year if you want to. I just used current year.
Try this:
Using the window function
row_number()
to order data by year and per journal, then we get only the first 3 inputs :This is a working solution if there is no gaps between years.
Demo here