2016-01-04 156 views
0

我有一個用作報表基礎的SQL查詢。報告顯示按年份,月份和燃料類型分組的燃料使用量。我想計算每種燃料類型的總量百分比,但我沒有太多的運氣。爲了計算整體的百分比,我需要能夠獲得所使用燃料的總量,而不管它在哪個組中,我似乎無法弄清楚如何做到這一點。這是我的查詢:SQL按組計算百分比

SELECT Year([DT1].[TransactionDate]) AS [Year], Month([DT1].[TransactionDate]) AS [Month], DT1.FuelType, Format(Sum(DT1.Used),"#.0") AS [Total Used],  
FROM (SELECT TransactionDate, FuelType, Round([MeterAfter]-[MeterBefore],2) AS Used FROM FuelLog) AS DT1 
WHERE (((DT1.TransactionDate) Between [Start Date] And [End Date])) 
GROUP BY Year([DT1].[TransactionDate]), Month([DT1].[TransactionDate]), DT1.FuelType 
ORDER BY Year([DT1].[TransactionDate]), Month(DT1.TransactionDate), DT1.FuelType; 

我試着添加以下作爲子查詢,但我得到一個錯誤,說子查詢返回多個結果。

(SELECT Sum(Round([MeterAfter]-[MeterBefore],2)) AS Test 
FROM Fuellog 
WHERE Year([Year]) and Month([Month]) 
GROUP BY Year([TransactionDate]), Month([TransactionDate])) 

一旦我得到所有燃料的總和,我需要將燃料用量除以兩種燃料的總量。我應該以不同的方式接近這個嗎?

回答

2

試試這個

SELECT A.[Year] 
     ,A.[Month] 
     ,A.[FuelType] 
     ,A.[Total Used] 
     ,(A.[Total Used]/B.[Total By Year Month]) * 100 AS Percentage 
    FROM 
(
    SELECT Year([DT1].[TransactionDate]) AS [Year] 
    , Month([DT1].[TransactionDate]) AS [Month] 
    , DT1.FuelType 
    , Format(Sum(DT1.Used),"#.0") AS [Total Used] 
    FROM (
     SELECT TransactionDate 
       , FuelType 
       , Round([MeterAfter]-[MeterBefore],2) AS Used 
      FROM FuelLog 
     ) AS DT1 
WHERE (((DT1.TransactionDate) Between [Start Date] And [End Date])) 
GROUP BY Year([DT1].[TransactionDate]), Month([DT1].[TransactionDate]),  DT1.FuelType 
ORDER BY Year([DT1].[TransactionDate]), Month(DT1.TransactionDate),  DT1.FuelType 
) A 
INNER JOIN 
    (
    SELECT Sum(Round([MeterAfter]-[MeterBefore],2)) AS [Total By Year Month] 
     , Year([TransactionDate]) AS [Year] 
     , Month([TransactionDate])) AS [Month] 
     FROM Fuellog 
    GROUP 
     BY Year([TransactionDate]) 
     , Month([TransactionDate])) 
) B 
    ON A.[Year] = B.[Year] 
    AND A.[Month] = B.[Month] 
+0

完美的感謝@vmachan!在ORDER BY的一個上有一個半角字符,但是當我刪除它時,查詢完美地運行了!感謝您的幫助。 – mack

+0

@mack,很高興幫助。我通過刪除錯誤的分號更新了答案。 – vmachan

2

你需要加入到總計 - 是這樣的(未經測試可能有錯別字)

SELECT 
    Year([DT1].[TransactionDate]) AS [Year], 
    Month([DT1].[TransactionDate]) AS [Month], 
    DT1.FuelType, 
    Format(Sum(DT1.Used),"#.0") AS [Total Used],  
    (Sum(DT1.Used)/FT.Total) * 100 AS Percent 
FROM (
    SELECT 
    TransactionDate, 
    FuelType, 
    Round([MeterAfter]-[MeterBefore],2) AS Used 
    FROM FuelLog 
) AS DT1 
JOIN (
    SELECT 
    Sum(Round([MeterAfter]-[MeterBefore],2)) AS Total 
    FuelType 
    FROM Fuellog 
    WHERE TransactionDate Between [Start Date] And [End Date] 
    GROUP BY FuelType 
) FT ON DT1.FuelType = FT.FeulType 
WHERE DT1.TransactionDate Between [Start Date] And [End Date] 
GROUP BY Year([DT1].[TransactionDate]), Month([DT1].[TransactionDate]), DT1.FuelType, FT.Total 
ORDER BY Year([DT1].[TransactionDate]), Month(DT1.TransactionDate), DT1.FuelType, FT.Total;