SQL计算分组依据中的百分比

时间:2016-01-04 15:15:10

标签: sql ms-access-2013

我有一个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 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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]