C#中的sql命令错误

时间:2013-07-21 20:37:06

标签: c# sql-server

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

  

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

我该如何解决?

2 个答案:

答案 0 :(得分:7)

问题是你的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 

答案 1 :(得分:1)

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

组函数用于创建汇总行,因此您的选择列要么必须是group by子句的一部分,要么是sum(x)或count(x)

之类的statmet的汇总类型

以下可能有用..

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