选择SUM a column and group by

时间:2017-04-13 06:53:35

标签: c# sql

我有2个表(tblGenerator和tblGeneratorLine)。 tblGenerator包含关于每个生成器的ingormation,tblGeneratorLine包含每个生成器每月的租金。我希望在一年内获得每台发电机的RentPayd总清单。我正在使用下面的代码,当我运行代码时,我得到了这个 错误:

  

在聚合和分组表达式中,SELECT子句可以包含   只聚合和分组表达式。 [Select clause = g,Zoon]

任何人都可以帮忙。

internal static DataTable getRentByYear(int year)
{
    string sql = "Select SUM(l.RentPayd) AS Payd, l.GenId, g.Zoon from tblGeneratorLine AS l INNER JOIN tblGenerator AS g on l.GenId=g.GenId where l.Year=@year Group By l.GenId Order By l.GenId";

    if (con.State == ConnectionState.Closed)
        con.Open();
    DataTable dt = new DataTable();
    try
    {
        SqlCeDataAdapter adp = new SqlCeDataAdapter();
        adp = new SqlCeDataAdapter(sql, con);
        adp.SelectCommand.Parameters.Add("@year", SqlDbType.Int).Value = year;
         adp.Fill(dt);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        con.Close();
    }
    return dt;
}

提取的SQL查询的位置是:

select SUM(l.RentPayd) AS Payd, l.GenId, g.Zoon
from tblGeneratorLine AS l
    INNER JOIN tblGenerator AS g on l.GenId = g.GenId
where l.Year = @year
group By l.GenId
order By l.GenId

4 个答案:

答案 0 :(得分:0)

正如错误所述,当使用group by时,select中未使用聚合函数的每个字段(例如sum)也应该在group by子句中。

因此,在您的情况下,您应该将g.Zoon添加到Group By

....  Group By l.GenId, g.Zoon ...

答案 1 :(得分:0)

您必须在group by子句中包含所有非聚合列 因此,如果通过g.zoon进行分组可以为您提供正确的结果,那么就像通过以下方式将其添加到组中一样简单:

   Group By l.GenId
   , g.Zoon 

如果没有那么你将需要使用CTE或subselect来获得l.GenId的总和,然后是g.zoon,例如:

Select T.SumPayd
, g.Zoon 
FROM tblGenerator AS g 
INNER JOIN
(   Select 
        SUM(l.RentPayd) AS SumPayd
        , l.GenId
    from tblGeneratorLine AS l 
    where l.Year=@year 
    Group By 
        l.GenId
) AS T
WHERE g.GenId = T.GenId 
Order By g.GenId

答案 2 :(得分:0)

您需要将g.Zoon添加到GROUP BY子句:

string sql = @"
SELECT   SUM(l.RentPayd) AS Payd
        ,l.GenId
        ,g.Zoon
FROM tblGeneratorLine AS l
    INNER JOIN tblGenerator AS g
        ON l.GenId = g.GenId
WHERE l.Year = @year
GROUP BY l.GenId
        ,g.Zoon
ORDER BY l.GenId
";

答案 3 :(得分:0)

在SQL中,选择l.GenId,g.Zoon和Sum(l.RentPayd)

在你的小组中,你只有l.GenId

g.Zoon不在你的小组中,它不是聚合(总和,数,最大等)

它必须是一个或另一个,或者你不能在select语句中拥有它。

如果您将多条记录分组为一行,您希望Zoon做什么?如果它们对于同一输出行必须相同,则将其放在group by子句中。否则,你将不得不求和,最大值或其他东西,具体取决于它是什么以及你想要什么。