0

我正在开发 ASP.NET 中的窗口应用程序。为了存储我使用 Excel 工作表的数据。Excel 工作表具有以下字段:

  • 状态
  • 观点

为了得到我有以下标准:

  • 金 - 7 分
  • 银牌 - 5 分
  • 铜牌 - 4 分

我想统计每个州获得的金牌、银牌和铜牌的总数。为此,我使用了以下查询:

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)”中的语法错误(缺少运算符)。

如何解决此错误?谢谢!

4

1 回答 1

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);
于 2013-09-20T11:59:42.490 回答