gpt4 book ai didi

c# - C#中的sql命令错误

转载 作者:行者123 更新时间:2023-11-30 19:42:14 26 4
gpt4 key购买 nike

我编写这段代码是为了从数据库中的两个表中检索一些信息。但是当我运行它时,我得到了这个错误

Column 'Eaten_food.Cardserial' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

代码:

 private void button8_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(WF_AbsPres_Food.Properties.Settings.Default.DbConnectionString))
{
con.Open();
SqlDataAdapter a = new SqlDataAdapter("SELECT Eaten_food.Cardserial , Eaten_food.Date , Eaten_food.Turn , Avb_food_count , Reserve_count from Reserve inner join Eaten_food on Reserve.Cardserial = Eaten_food.Cardserial group by Eaten_food.Date", con);
SqlCommandBuilder comdBuilder = new SqlCommandBuilder(a);
DataTable t = new DataTable();
//t.Locale = System.Globalization.CultureInfo.InvariantCulture;
a.Fill(t);
bindingSource3.DataSource = t;

/// bind the grid view with binding source
Reserve_dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
Reserve_dataGridView.ReadOnly = true;
Reserve_dataGridView.DataSource = bindingSource3;

Reserve_dataGridView.DataSource = t;
con.Close();
}
}

我该如何解决?

最佳答案

问题出在你的sql查询上。如果您使用 Group By,则无法选择未分组或未聚合的列(例如,使用 Min/Max/Avg/Count)。

因此您可以通过这种方式使其工作,例如,在此处更改您的旧查询:

SELECT eaten_food.cardserial, 
eaten_food.date,
eaten_food.turn,
avb_food_count,
reserve_count
FROM reserve
INNER JOIN eaten_food
ON reserve.cardserial = eaten_food.cardserial
GROUP BY eaten_food.date

到:

SELECT MIN(eaten_food.cardserial)AS Cardserial, 
eaten_food.date,
MIN(eaten_food.turn) AS Turn,
SUM(avb_food_count) AS SumFoodCount,
SUM(reserve_count) AS SumReserveCount
FROM reserve
INNER JOIN eaten_food
ON reserve.cardserial = eaten_food.cardserial
GROUP BY eaten_food.date

关于c# - C#中的sql命令错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17776656/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com