如何编写 SqlCommand 在 ASP.NET 的列中选择前 3 个重复次数最多的值
Posted
技术标签:
【中文标题】如何编写 SqlCommand 在 ASP.NET 的列中选择前 3 个重复次数最多的值【英文标题】:How do I write a SqlCommand that selects top 3 most repeated values in a column in ASP.NET 【发布时间】:2019-04-19 03:59:10 【问题描述】:我正在尝试从日期选择器“从-到”格式检索最畅销的商品。我有这个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();
【问题讨论】:
【参考方案1】:您在 Select 列表中的 SOLD
列之后出现语法错误,缺少逗号 (,),并将 order by 子句移到最后,将 where 子句移到 Group 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 注入。
【讨论】:
我在 where 附近的语法不正确。 "关键字'WHERE'附近的语法不正确。'" 只需在SELECT
子句SELECT TOP 3 Sold, Count(Sold).
中的Sold
列之后添加一个逗号(,),并将顺序移到where 子句之后。检查更新的答案
请用您遇到的错误更新问题。另外,添加 from 和 to 日期后生成的 sql 查询是什么?
where
子句应出现在group by
之前。交换它们,其他一切都应该没问题。【参考方案2】:
SELECT TOP 3 Sold, COUNT(Sold) AS MOST_FREQUENT 从 Transactions WHERE Dates between '"+Convert.ToDateTime(txtDate.Text)+"' 和 '"+Convert.ToDateTime(txtDate2.Text)+"' GROUP BY Sold ORDER BY COUNT(Sold) DESC
Group by 和 order by 应该在 where 子句之后。
【讨论】:
以上是关于如何编写 SqlCommand 在 ASP.NET 的列中选择前 3 个重复次数最多的值的主要内容,如果未能解决你的问题,请参考以下文章
如何在我的 ASP.NET 应用程序中避免 SQL 注入攻击?
如何在 asp.net core 中编写自定义 actionResult