带条件检索id

Retrieve id with condition

我正在尝试通过单击为学生分配学院。此分配需要有条件才能分配给学生特定的学院。

这是我的数据库 tables:

tblAcademy

    Acad_id name  seat_available
   ------------------------------
    1       A        2
    2       B        2
    3       C        1
    4       D        5
    5       E        3

tblStudent

    stud_Id name   `stud_purcentage` `stud_result`   acad_id
   ----------------------------------------------------------
     1       Alex     100               `Pass`
     2       Lee      80.5              `Pass`
     3       Lea      40.3              `Fail`
     4       Loane    10                `Fail`
     5       john     50                `Pass`

tblAcademy_selection

   stud_id Acad_id order_preference
   --------------------------------
    1      1          1
    1      3          2
    4      3          1
    4      2          2
    4      4          3

Acad_idtblAcademy 的外键。如果不遵守条件,acad_id 可以保持为空,学生可能没有学院。

tblAcademy selection 中显示一个学生可以 select 多个学院,但只需要分配一个给他们。

分配必须基于学院可用的席位,以及通过的人,并从最好的百分比到最差的百分比分配。

到目前为止,我已经能够从最好的学生到最差的学生以及通过的学生进行检索。然后我将这些学生 ID 加入 tblAcademy_selection.

SqlConnection dbcon = new SqlConnection(_conString);

SqlCommand scmd = new SqlCommand();
scmd.CommandText = "SELECT stud_Id, stud_fname, stud_purcentage, stud_totalMarks FROM tblStudent WHERE stud_result = 'Pass' ORDER BY stud_purcentage DESC";
scmd.Connection = dbcon;

SqlDataAdapter da = new SqlDataAdapter(scmd);
DataTable dt = new DataTable();

dbcon.Open();

da.Fill(dt);

string[] array = new string[dt.Rows.Count];

// foreach (DataRow row in dt.Rows)
for (int a = 0; a < dt.Rows.Count; a++)
{
    // studID = row["stud_Id"].ToString();
    array[a] = dt.Rows[a]["stud_Id"].ToString();

    SqlCommand scmd2 = new SqlCommand();
    scmd2.CommandText = "SELECT * FROM tblAcademy ta JOIN tblAcademy_Selection tas ON ta.acad_Id = tas.acad_Id WHERE stud_Id IN ('" + array[a] + "')";
    scmd2.Connection = dbcon;

    SqlDataAdapter da2 = new SqlDataAdapter(scmd2);
    DataTable dt2 = new DataTable();
    da2.Fill(dt2);

    string[] array2 = new string[dt2.Rows.Count];

    for (int a2 = 0; a2 < dt2.Rows.Count; a2++)
    {
        array2[a2] = dt2.Rows[a2]["stud_Id"].ToString();

        SqlCommand scmd3 = new SqlCommand();
    }
}

在我的第一个 SQL 陈述中,我 select 编辑了那些百分比最高的人和那些通过并存储在数组中的人。 使用 for 循环,我正在检索数据 table value

在第二个 SQL 语句中,我与 tblAcademytblAcademy_selection 进行了连接,其中 tblAcademy_selection.stud_id 位于我在第一条声明。

我很难应用这样的条件:如果学生选择的学院座位已满,则移至第二选择,如果第二选择已满,则移至第三,依此类推。

如果他选择的所有学院席位都已满,则学生可能没有学院。

您必须在 SQL 语句中应用过滤条件以过滤掉 tblAcademy.seat_available = 0 的记录。

然后根据顺序偏好生成 row_number 或排名,并检索生成的 row_number =1 的记录。

像这样:

SELECT * FROM 
(
SELECT tas.*, DENSE_RANK() OVER (PARTITION BY stud_id ORDER BY order_preference) AS row_id 
FROM tblAcademy ta 
JOIN tblAcademy_Selection tas ON ta.acad_Id = tas.acad_Id 
WHERE ta.seat_available >0 and stud_Id IN ('" + array[a] + "')"
) DTL 
WHERE row_id = 1