如何编写一个SqlCommand,在ASP.NET中的列中选择前3个最重复的值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何编写一个SqlCommand,在ASP.NET中的列中选择前3个最重复的值相关的知识,希望对你有一定的参考价值。
我试图从日期选择器“从 - 到”格式检索最畅销的项目。我有这个SqlCommand
我试图运行但它不工作。
SqlCommand cmd = new SqlCommand("SELECT TOP 3 Sold COUNT(Sold) AS MOST_FREQUENT FROM Transactions GROUP BY Sold ORDER BY COUNT(Sold) DESC WHERE Dates Between'" + Convert.ToDateTime(txtDate.Text) + "' and '" + Convert.ToDateTime(txtDate2.Text) + "'", con);
更新
("SELECT TOP 3 Sold, COUNT(Sold) AS MOST_FREQUENT FROM Transactions GROUP BY Sold WHERE Dates Between '"+Convert.ToDateTime(txtDate.Text)+"' and '"+Convert.ToDateTime(txtDate2.Text)+"' ORDER BY COUNT(Sold) DESC", con);
更新2完整代码
protected void btnApply_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["POS_SystemConnectionString2"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
if (txtDate.Text != null && txtDate2.Text != null)
{
SqlCommand cmd = new SqlCommand("SELECT TOP 3 Sold, COUNT(Sold) AS MOST_FREQUENT FROM Transactions WHERE Sold GROUP BY Dates Between '"+Convert.ToDateTime(txtDate.Text)+"' and '"+Convert.ToDateTime(txtDate2.Text)+"' ORDER BY COUNT(Sold) DESC", con);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count != 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
}
}
con.Close();
}
}
答案
您在选择列表中的SOLD
列之后缺少逗号(,)的语法错误,并且还在Group by之前的end和where子句中移动order by子句,如下所示:
子句的顺序应该是SELECT,WHERE,GROUP BY,Order by
protected void btnApply_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["POS_SystemConnectionString2"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
if (txtDate.Text != null && txtDate2.Text != null)
{
SqlCommand cmd = new SqlCommand("SELECT TOP 3 Sold, COUNT(Sold) AS MOST_FREQUENT FROM Transactions WHERE Dates Between '"+Convert.ToDateTime(txtDate.Text)+"' and '"+Convert.ToDateTime(txtDate2.Text)+"' GROUP BY Sold ORDER BY COUNT(Sold) DESC", con);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count != 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
}
}
con.Close();
}
此外,您必须使用参数化查询,而不是内联连接参数值以避免SQL注入。
另一答案
SELECT TOP 3已售出,COUNT(已售出)AS MOST_FREQUENT FROM Transactions WHERE日期在'“+ Convert.ToDateTime(txtDate.Text)+”'和'“+ Convert.ToDateTime(txtDate2.Text)+”'GROUP BY Sold Ororder BY COUNT(已售出)DESC
group by和order by应该在where子句之后。
以上是关于如何编写一个SqlCommand,在ASP.NET中的列中选择前3个最重复的值的主要内容,如果未能解决你的问题,请参考以下文章
如何在我的 ASP.NET 应用程序中避免 SQL 注入攻击?