在1行中合并数据

时间:2018-07-10 08:13:02

标签: sql sql-server sql-server-2017

初始数据示例:

 Project   |   Modified   | LastModify |
 ---------------------------------------
 Project 1 |  12.01.2018  |      3     |
 Project 2 |  10.02.2017  |      2     |
 Project 1 |  15.01.2018  |      2     |
 Project 1 |  18.01.2018  |      1     |
 Project 2 |  15.02.2017  |      1     |

我通过查询得到了这个结果:

SELECT *
, Row_number() over (partition by Project order by Modified desc ) as LastModify
FROM Table_A

我需要添加列,其中第Lastmodify = 1列的行必须先修改项目日期

即每个Project的第一个修改日期和最后修改日期都可获得1行

预期结果如下:

 Project   |   Modified   | LastModify | FirstModifyDate|
 ----------------------------------------------------
 Project 1 |  18.01.2018  |      1     |  12.01.2018   |
 Project 2 |  15.02.2017  |      1     |  10.02.2017   |

我该怎么做?

2 个答案:

答案 0 :(得分:1)

如果您的Sql服务器版本等于或高于2012,则可以使用:

SELECT *
, Row_number() over (partition by Project order by Modified desc ) as LastModify
, First_value(Modified) over (partition by Project order by Modified asc) [FirstModifyDate]
FROM Table_A

答案 1 :(得分:0)

我已经创建了一个像您的数据一样的表,并应用了可能有帮助的查询。 you can refer to this image

SELECT new.project
    ,new.times
    ,new.pdate
    ,sec.p1date
FROM new
INNER JOIN (
    SELECT child.project AS p
        ,child.pdate AS p1date
    FROM new AS child
    INNER JOIN new ON child.project = new.project
    GROUP BY child.project
    HAVING child.times = MAX(child.times)
    ) AS sec ON sec.p = new.project
WHERE new.times = 1