[英]Select SUM a column and group by
我有2個表(tblGenerator和tblGeneratorLine)。 tblGenerator包含有關每個生成器的信息,tblGeneratorLine包含每個生成器每月的租金。 我想獲得一年內每個發電機的總RentPayd列表。 我正在使用下面的代碼,當我運行代碼時出現此錯誤:
在聚合和分組表達式中,SELECT子句只能包含聚合和分組表達式。 [選擇子句= 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
正如錯誤所言,當使用group by時,select中未使用聚合函數的每個字段(例如sum
)也應該在group by子句中。
因此,在您的情況下,您應該將g.Zoon
添加到Group By
:
.... Group By l.GenId, g.Zoon ...
您必須在group by子句中包括所有未聚合的列。因此,如果按g.zoon分組可以為您提供正確的結果,則就像將其添加到group by一樣簡單:
Group By l.GenId
, g.Zoon
如果不是,那么您將需要使用CTE或子選擇來首先通過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
您需要將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
";
在您的SQL中,選擇l.GenId,g.Zoon和Sum(l.RentPayd)
在您的分組依據中,您只有l.GenId
g.Zoon不在您的分組依據中,也不是總計(總數,計數,最大值等)
它必須是另一個,否則您不能在select語句中使用它。
如果您將多條記錄歸為一行,那么您想對Zoon做什么? 如果對於同一輸出行它們都必須相同,則將其放在group by子句中。 否則,您將必須求和,最大值或其他值,具體取決於它是什么以及想要什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.