如何将一 SQL 列转换为同一行的多列?

How to transform one SQL column into multiple columns on the same row?

我在 Excel 中的 Progress ODBC 中工作,我有一个数据集,当前包含该对象的 ID、对象类型和结果。数据集如下所示:

EveNumber                   ObjName                                   TroValue
1234               818 Artwork typeset duration                       00:30:00
1234               818 Artwork Estimated typeset duration             00:40:00

我正在尝试使用以下 CASE WHEN

将这些数据全部放在一行中
Select

Event_0.EveNumber
,(CASE WHEN Object_0.ObjName = '818 Artwork typeset duration' THEN TemplateRunObject_0.TroValue ELSE NULL END) AS 'BookedTime'
,(CASE WHEN Object_0.ObjName = '818 Artwork Estimated typeset duration' THEN TemplateRunObject_0.TroValue ELSE NULL END) AS 'EstimatedTime'

我发现这会导致阶梯式结果。所以我的 returned 数据仍然以多行返回。很像这样:

EveNumber                BookedTime                    EstimatedTime              
1234                      00:30:00                                                     
1234                                                     00:40:00     

我可以做些什么来 return 这一结果吗?

使用条件聚合

Select
Event_0.EveNumber
,max(CASE WHEN Object_0.ObjName = '818 Artwork typeset duration' THEN TemplateRunObject_0.TroValue ELSE NULL END) AS 'BookedTime'
,max(CASE WHEN Object_0.ObjName = '818 Artwork Estimated typeset duration' THEN TemplateRunObject_0.TroValue ELSE NULL END) AS 'EstimatedTime'
group by Event_0.EveNumber

您需要 GROUP BY:

Select Event_0.EveNumber,
       MAX(CASE WHEN Object_0.ObjName = '818 Artwork typeset duration' THEN TemplateRunObject_0.TroValue ELSE NULL END) AS BookedTime,
       MAX(CASE WHEN Object_0.ObjName = '818 Artwork Estimated typeset duration' THEN TemplateRunObject_0.TroValue ELSE NULL END) AS EstimatedTime
FROM . . .
GROUP BY Event_0.EveNumber;

注意:SQL中使用单引号来定义字符串和日期常量。不要将它们用于列别名。有一天,当您使用单引号引用一列但它被解释为字符串时,这只会给您带来麻烦。