简体   繁体   中英

How to concat two rows into single row depending on index

I'm having distinct years in my select query. now i want to concat first and second year into one row and so on. How to achieve this?

This is what I have

在此处输入图片说明

You may solve this using a self-join. The join condition is that the year from the first table is one less the year of the second table. This approach handles well the edge case of the starting and ending years only matching on one side.

SELECT
CONCAT(CAST(t1.year AS CHAR(4)), '-', CAST(t2.year AS CHAR(4))) AS year
FROM yourTable t1
INNER JOIN yourTable t2
    ON t2.year = t1.year + 1;

    year
1   2015-2016
2   2016-2017
3   2017-2018

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