首先:为什么 Operation.StatusID 是 Text 类型的,当它填充来自整数字段的值时?关于 RegionID 的问题也可能相同,但由于此处未列出 Region 表,我无法确定,在这种特殊情况下,您可能需要 Text。但是将 Operation.StatusID 作为 Text 是完全不合理的,并且会给您带来性能损失。
尽管如此,有一个古老的技巧,称为旋转,但它只适用于固定数量的列,在你的情况下 - 调查:
SELECT
Sample.BuildingID,
MAX(Sample.BuildingName_EN) BuildingID,
MAX(CASE WHEN Operation.SurveyTypeID=1 THEN Operation.StatusID ELSE " " END) AS Survey1,
MAX(CASE WHEN Operation.SurveyTypeID=2 THEN Operation.StatusID ELSE " " END) AS Survey2,
MAX(CASE WHEN Operation.SurveyTypeID=3 THEN Operation.StatusID ELSE " " END) AS Survey3
FROM Sample,Operation
WHERE Operation.SampleID=Sample.ID
GROUP BY Sample.BuildingID
更新:为确保此解决方案的可扩展性,您必须在每次使用另一个查询之前生成此查询:
SELECT ' SELECT Sample.BuildingID,MAX(Sample.BuildingName_EN) BuildingID,'
UNION ALL
SELECT concat(' MAX(CASE WHEN Operation.SurveyTypeID=',SurveyType.ID,' THEN Operation.StatusID ELSE " " END) AS "',SurveyType.LongName,'",') from SurveyType
UNION ALL
SELECT '0 as dummy FROM Sample,Operation WHERE Operation.SampleID=Sample.ID GROUP BY Sample.BuildingID'
或者,对于 Oracle 和 SQLite:
SELECT ' SELECT Sample.BuildingID,MAX(Sample.BuildingName_EN) BuildingID,'
UNION ALL
SELECT ' MAX(CASE WHEN Operation.SurveyTypeID='||SurveyType.I||' THEN Operation.StatusID ELSE " " END) AS "'||SurveyType.LongName||'",' from SurveyType
UNION ALL
SELECT '0 as dummy FROM Sample,Operation WHERE Operation.SampleID=Sample.ID GROUP BY Sample.BuildingID'