我正在使用ASP.NET中的窗口应用程序。要存储数据我正在使用Excel工作表。 Excel工作表包含以下字段:
为了获得以下标准:
我想计算每个州获得的金牌,银牌和铜牌总数。为此,我使用了以下查询:
OdbcConnection con = new OdbcConnection(ConfigurationManager.ConnectionStrings["SportTech"].ConnectionString);
//string query = "select STATE,sum(Point) as MEDAL from [Sheet2$] Group by STATE order by sum(Point) desc";
string query = "SELECT STATE,SUM(Point) AS MEDAL,SUM(CASE WHEN Point = 7 THEN 1 ELSE 0 END) AS GoldCount,SUM(CASE WHEN Point = 5 THEN 1 ELSE 0 END) AS SilverCount,SUM(CASE WHEN Point = 4 THEN 1 ELSE 0 END) AS BronzeCount FROM [Sheet2$] GROUP BY STATE ORDER BY SUM(Point) DESC";
OdbcCommand cmd = new OdbcCommand(query, con);
OdbcDataAdapter da = new OdbcDataAdapter(cmd);
con.Open();
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
但它显示错误:
错误[42000Օ] [Microsoft] [ODBC Excel驱动程序]语法错误(缺失 运算符)在查询表达式'SUM(CASE WHEN Point = 7 THEN 1 ELSE 0 END)”
如何解决此错误? 谢谢!
答案 0 :(得分:1)
如果我理解正确你可以试试这个。我使用OleDB而不是Odbc
string constring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\\statetest.xls;Extended Properties=\"Excel 8.0;HDR=YES\"";
OleDbConnection con = new OleDbConnection(constring);
string query = "select STATE,sum(IIF(point = 7,1,sum(IIF(point = 5,1,sum(IIF(point = 4,1,0)))))) as PointsPerState,sum(IIF(point = 7,1,0)) as Gold, sum(IIF(point = 5,1,0)) as Silver, sum(IIF(point = 4,1,0)) as Bronce from [Sheet2$] group by STATE";
OleDbCommand cmd = new OleDbCommand(query, con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
con.Open();
DataTable dt = new DataTable();
da.Fill(dt);