Microsoft Access - Sum If条件

时间:2017-08-29 14:48:35

标签: sql ms-access

我正在尝试创建一个总结if语句。该声明应该查看一个列(材料),看它是否标记为Ore或Waste。然后它查看另一列(Tonnage)并对该列中的值求和。

在我尝试添加此总和if语句之前。当我现在运行它时,它会要求haulage.tonnage和haulage.material参数。

代码如下:

SELECT
            [WeekCounter], 
            [WeekStartDate], 
            [WeekEndDate], 
            [Level], 
            Sum([Ore Round]) AS SumOreRound, 
            Sum([Ore Advancement]) AS SumOreAdvancement,
            Sum( IIF ([Material] = "Ore", [Tonnage], 0)) AS [Ore Tonnes],
            Sum([Waste Round]) AS SumWasteRound, 
            Sum([Waste Advancement]) AS SumWasteAdvancement, 
            Sum( IIF ([Material] = "Waste", [Tonnage], 0)) AS [Waste Tonnes], 
            Sum([Production Round]) AS ProductionRound, 
            Sum([Production Advancement]) AS SumProductionAdvancement

FROM (SELECT 
            Rounds.[Ore Round], 
            Rounds.[Ore Advancement], 
            Week_Numbers.[WeekCounter],
            Rounds.[Waste Round], 
            Rounds.[Waste Advancement], 
            Rounds.[Production Round], 
            Rounds.[Production Advancement], 
            Week_Numbers.WeekStartDate, 
            Week_Numbers.WeekEndDate, 
            Rounds.[Level],
            Haulage.[Tonnage],
            Haulage.[Material]

FROM Rounds INNER JOIN Week_Numbers 
            ON (Rounds.[Date] <= Week_Numbers.WeekEndDate) 
            AND (Rounds.[Date] >= Week_Numbers.WeekStartDate))


GROUP BY 
           [WeekCounter],
           [WeekStartDate],
           [WeekEndDate], 
           [Level];

谢谢

1 个答案:

答案 0 :(得分:0)

根据评论, Haulage 似乎与 Rounds Week_Numbers 无关。如果是这样,请考虑使用INNER JOIN通过逗号分隔 Haulage INNER JOIN子句下的FROM全部交叉加入表格。

请注意:交叉连接在两个集合之间返回cartesian product。因此, Haulage 行的每个组合将与内部联接的每次返回配对。对于大型桌子,这可能会变得非常大(例如,1000行的Haulage乘以1,000行的内部连接会产生1,000,000行)。

SELECT w.[WeekCounter], 
       w.[WeekStartDate], 
       w.[WeekEndDate], 
       r.[Level], 
       Sum(r.[Ore Round]) AS SumOreRound, 
       Sum(r.[Ore Advancement]) AS SumOreAdvancement,
       Sum(IIF(h.[Material] = 'Ore', h.[Tonnage], 0)) AS [Ore Tonnes],
       Sum(r.[Waste Round]) AS SumWasteRound, 
       Sum(r.[Waste Advancement]) AS SumWasteAdvancement, 
       Sum(IIF(h.[Material] = 'Waste', h.[Tonnage], 0)) AS [Waste Tonnes], 
       Sum(r.[Production Round]) AS ProductionRound, 
       Sum(r.[Production Advancement]) AS SumProductionAdvancement

FROM Haulage h, 
     Rounds r INNER JOIN Week_Numbers w
                ON (r.[Date] <= w.WeekEndDate) 
               AND (r.[Date] >= w.WeekStartDate))
GROUP BY 
       w.[WeekCounter],
       w.[WeekStartDate],
       w.[WeekEndDate], 
       r.[Level];