如何在CTE中将两行合并为一行

时间:2018-12-18 11:41:06

标签: sql-server common-table-expression

我正在像这样的CTE中获取数据。

在这里,我为每个ActivityId获得两条记录,我想要实现的是从两行中创建两条记录。在r2 = 1的行中,我只需要将RDate用作Todate,将ActualProgress用作endprogress,将PlannedProgress用作endplannedprogress,因为这是在这两行中唯一会更改的值。

我正在CTE中获取这些数据。

WITH CTE as(SELECT row_number() over (partition by pmaph.ActivityId order by date) r1, row_number() over (partition by pmaph.ActivityId order by date desc) r2,pma.PlanEndDate as PlanEndDate ,pma.PlanStartDate as PlanStartDate,pmaph.ActivityId,pmaph.ProjectMilestoneActivProgHist_Id as ProMileAvtiID,umd.UOM_Name as UomName, pmm.MilestoneName as MilestoneName,pma.ActivityName as ActivityName ,pmp.ProjectName as ProjectName, Replace((rtrim(ltrim(Convert(varchar(12),Cast(pmaph.Date as Datetime),106)))),' ','-') as RDate, isnull(pmaph.Actual_Progress,0) as ActualProgress,isnull(pmaph.Planned_Progress,0) as PlannedProgress FROM ProjectMilestoneActivityProgressHistory as pmaph left join dbo.PM_Project as pmp on pmaph.ProjectId=pmp.ProjectId left join dbo.PM_Activity as pma on pmaph.ActivityId=pma.ActivityId  left join dbo.PM_Milestone  as pmm on pmaph.MilestoneId=pmm.MilestoneId left join dbo.UOMDetail as umd on pma.UOM_Id=umd.UOM_Id where pmaph.Client_Id=@ClientId
)
select  * from CTE where r1=1 or r2=1

2 个答案:

答案 0 :(得分:0)

您可以对ActivityId进行分组,并包含MAX(RDate)和MAX(ActualProgress),每个ActivityId仅应返回一行。

答案 1 :(得分:0)

也许这可以给您提示。确保保留您的SQL格式。

for i in range(0,100):
    #code to initiate simulation
    print(startValues, 'ParameterSet:', ParameterSet,'time:', stoptime)
    np.save('out1.npy', output_data)