2

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

列“Eaten_food.Cardserial”在选择列表中无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

代码:

 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();
        }
    }

我该如何解决?

4

2 回答 2

7

问题是你的 sql 查询。如果使用Group By,则无法选择未分组或未聚合的列(使用 fe 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 
于 2013-07-21T20:40:54.690 回答
1

您的 SQL 语句本身有问题。我会将它复制到 SQL 管理工作室并进行调试。

group 功能是创建摘要行,因此您的选择列需要是 group by 子句的一部分,或者是 sum(x) 或 count(x) 等统计类型的摘要类型

以下可能有效..

SELECT  Eaten_food.Cardserial ,
        Eaten_food.Date ,
        Count(Eaten_food.Turn) ,
        sum(Avb_food_count) ,
        sum(Reserve_count)
FROM    Reserve
        INNER JOIN Eaten_food ON Reserve.Cardserial = Eaten_food.Cardserial
GROUP BY Eaten_food.Date, Eaten_food.CardSerial
于 2013-07-21T20:44:42.823 回答