在MSaccess中显示同一行中的相关行

时间:2017-08-09 13:19:01

标签: sql ms-access aggregate-functions

我有一组相关的行,我需要在一行中显示。例如,我拥有的数据位于不同的行中。

"ID"   RecordDate   "ExpType"  "OrigBudget"  "ActualCost"   
1001    1-5-2017    Hardware    $ 5000                    
1001    2-6-2017    Hardware                    $ 5200   

原始预算在较早时间被批准用于相同记录,但实际成本通常不同,并在以后记录。我希望输出为

ProjectID YearofEntry ExpenseType        OrgBudget  ActualCost  <BR>
 1001          2017       Hardware        $ 5000     $ 5200       <BR>

我已经尝试过基于ExpenseType和ProjectId聚合它的组查询,但到目前为止还没有成功将它集成到一行。

2 个答案:

答案 0 :(得分:2)

如果每个ExpType总共只有两行 - 一个包含原始预算,另一个包含实际费用 - 您只需使用GROUP BY

    SELECT ID               AS ProjectID
          ,YEAR(RecordDate) AS YearofEntry
          ,ExpType          AS ExpenseType
          ,MAX(OrigBudget)  AS OrgBudget
          ,MAX(ActualCost)  AS ActualCost
      FROM yourtable
  GROUP BY ID
          ,YEAR(RecordDate)
          ,ExpType

答案 1 :(得分:0)

试试这个:

SELECT ID,
       Year([RecordDate]) AS YEARofEntry,
       ExpType,
       Sum(OrigBudget) AS SumOfOrigBudget,
       Sum(ActualCost) AS SumOfActualCost
FROM youtable
GROUP BY ID,
         Year([RecordDate]),
         ExpType;