所以我有一个包含两个复选框列表的页面(C#ASP.net),一个包含一个简短的需求列表,另一个包含一个愿望列表。可以在两个列表中检查多个值。在数据库中,我有一个名为“Info”的表,其中包含“ID”,“系统”,“需求”和“愿望”列。它看起来有点像左上角的第一个表: https://docs.google.com/spreadsheets/d/18mybB32cAMSi7dX49CFyZB2CrS3yI_MoynM4pr8acew/edit#gid=0
该页面的目的是允许用户选择需求和愿望,并且页面返回可能系统的列表。该列表将按需求进行过滤(如果系统不满足需求,则根本不需要显示),然后按按每个系统满足的愿望数量排序。
我到目前为止的代码只能按需求过滤数据库(在CheckBoxList1中选择)。在CheckBoxList1中选择了愿望。我只是在调整现有查询时遇到困难,也包括匹配需求量的排序。是否可以使用单个查询?如果没有,我应该改变什么?
string query = "SELECT DISTINCT System FROM Info";
int numSelected = 0;
string condition = string.Empty;
foreach (ListItem li in CheckBoxList1.Items)
{
if (li.Selected)
{
numSelected = numSelected + 1;
}
}
foreach (ListItem item in CheckBoxList1.Items)
{
condition += item.Selected ? string.Format("'{0}', ", item.Value) : "";
}
if (!string.IsNullOrEmpty(condition))
{
condition = string.Format(" where Demand IN ({0}) GROUP BY System HAVING count(*) = {1}", condition.Substring(0, condition.Length - 2), numSelected);
}
SqlCommand cmd = new SqlCommand(query + condition);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
感谢您花时间看我的问题,我真的很感激!我会尽力回答任何问题。
答案 0 :(得分:0)
我希望我能正确理解这个问题。试试这个
更改您的查询
string query = "SELECT DISTINCT Systeem, count(*) FROM Eisen";
添加order by子句
if (!string.IsNullOrEmpty(condition)/* && !string.IsNullOrEmpty(condition2)*/)
{
condition = string.Format(" where Eis IN ({0}) GROUP BY Systeem HAVING count(*) = {1}", condition.Substring(0, condition.Length - 2), numSelected/*, condition2.Substring(0, condition2.Length - 2)*/);
}
string orderBy = string.Format(" ORDER BY count(*)");
SqlCommand cmd = new SqlCommand(query + condition + orderBy);
尝试构建如下的查询并检查
SELECT system
, system + ' (Fulfills ' + CONVERT(NVARCHAR, COUNT(*)) + ' wishes)' AS [Eligible systems]
,(SELECT Demands + ',' AS [text()] FROM info WHERE system =i.system FOR XML PATH('')) AS Demands
,(SELECT wishes + ',' AS [text()] FROM info WHERE system =i.system FOR XML PATH('')) AS Wishes
FROM info i
WHERE Demands in ('1','2','3')
AND wishes in ('1','2','3','4')
GROUP BY system
Order By COUNT(*)