将8个其他查询中的数据转换为相同结构的新查询

时间:2012-08-30 14:06:41

标签: sql group-by append ms-access-2010

我有8个查询执行计算并将结果保存在其中一列中。

每个查询的列标题遵循相同的结构;

CompanyYearAssetID, CompanyName, AssetName, Year, DatapointID, NameOfWhateverWasCalculated

在每次计算中,将相同的DatapointID分配给结果。例如;

CompanyYearAssetID, CompanyName, AssetName, Year, DatapointID, ReservoirOIL
10001             , CompanyA   , Asset1   , 2011, 105014     , 5
10002             , CompanyB   , Asset1   , 2011, 105014     , 3
10003             , CompanyC   , Asset1   , 2011, 105014     , 0

计算列的名称及其DatapointID是;

  • UnallocatedOIL 105014
  • WellworkOIL 105015
  • ReservoirOIL 105016
  • AnnualShutdownOIL 105017
  • FailureUnplannedPlantOIL 105018
  • PlantPlannedMaintenanceOIL 105019
  • ExportOIL 105020
  • MarketOIL 105039

我想创建一个查询,以便使用列标题

将所有结果理想地放入一个表中
CompanyYearAssetID, DatapointID, DatapointValue

有没有人知道我如何构建这个?

这里只是你需要它们是8个查询名称;

  1. PE_Field_UnallocatedOIL
  2. PE_Field_WellworkOIL
  3. PE_Field_ReservoirOIL
  4. PE_Field_AnnualShutdownOIL
  5. PE_Field_FailureUnplannedPlantOIL
  6. PE_Field_PlantPlannedMaintenanceOIL
  7. PE_Field_ExportOIL
  8. PE_Field_MarketOIL

1 个答案:

答案 0 :(得分:0)

如果查询1和查询2都返回相同的数据,就像这样

CompanyYearAssetID, CompanyName, AssetName, Year, DatapointID, ReservoirOIL
10001             , CompanyA   , Asset1   , 2011, 105014     , 5
10002             , CompanyB   , Asset1   , 2011, 105014     , 3
10003             , CompanyC   , Asset1   , 2011, 105014     , 0


SELECT * FROM (
   Select * from Query1
   UNION ALL
   Select * from Query2)

因此,此查询的结果将是

CompanyYearAssetID, CompanyName, AssetName, Year, DatapointID, ReservoirOIL
10001             , CompanyA   , Asset1   , 2011, 105014     , 5
10002             , CompanyB   , Asset1   , 2011, 105014     , 3
10003             , CompanyC   , Asset1   , 2011, 105014     , 0
10001             , CompanyA   , Asset1   , 2011, 105014     , 5
10002             , CompanyB   , Asset1   , 2011, 105014     , 3
10003             , CompanyC   , Asset1   , 2011, 105014     , 0

您像普通表一样查询

 SELECT * FROM (
       Select * from Query1
       UNION ALL
       Select * from Query2)
where Year = 2011 AND ReservoirOIL > 0