重新排列SQL查询结果以正确显示

时间:2012-02-29 12:01:23

标签: c# asp.net sql

我有一个特定查询的结果,我必须在我的网页的List控件中显示。

查询1结果:
4 items in descending order
查询2结果:
Top 1 result

实际上,我必须显示第一个查询的第一个结果,第一个结果来自第二个查询,然后是第一个查询结果中剩下的三个结果。

最初,我想重新排列行,但我认为在数据控件的ItemTemplate中不可能实现,因为不能更改各行。

我是否应该以某种形式编写查询,并按顺序给出结果,这样可以显示正确的项目顺序? 例如:
Take the first result from top 4 item +
Find the second result +
Three items (minus the top one already that has been already extracted)

有什么建议吗?

修改

1st class: (has 4 student)

Tom (Has highest score)
Rex (Hss second highest score)
Rambo (HAs 3rd highest score)
Betty (Has least score)

2nd class: (has 1 student)

Spooky (Has the highest score)

Required result order in DataControl:

Tom
Spooky
Rex
Rambo
Betty

2 个答案:

答案 0 :(得分:1)

这种方式你可以把第一个选择中的第一个和第二个中的第一个选择 和其他2首先选择;

首先你的查询返回:

public DataTable query1()
{
              DataTable dt = new DataTable();

                #region YOUR SQL1

                qs.Execute();
                dt = qs.Return;

                return dt1;
}

public DataTable query2()
{
              DataTable dt = new DataTable();

               #region YOUR SQL2

                qs.Execute();
                dt = qs.Return;

                return dt2;
}

您应该创建一个View State DataTable格式,就像您从Slect返回的DataTable一样。 EXEXMPLE:

public DataTable _VS_RETURN_FORMAT
{
    get
    {
        if (ViewState["_VS_RETURN_FORMAT] == null)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("field1");
            dt.Columns.Add("field2");

            ViewState["_VS_RETURN_FORMAT"] = dt;
        }
        return (DataTable)ViewState["_VS_RETURN_FORMAT"];
    }
    set
    {
        ViewState["_VS_RETURN_FORMAT"] = value;
    }
}

您应该能够使用DataRow控制数据表结果。例:

         DataTable dt1 = new DataTable();
        DataTable dt2 = new DataTable();

            dt1 = SelectQuery1();
            dt2 = SelectQuery2();


            //Create a new DataRow  Like  your ViewState
            DataRow dr = _VS_RETURN_FORMAT;


            //Adding  to the fields the value that your need 

            dr["field1"] = dt1.Row[0][0];
            dr["field2"] = dt1.Row[0][1];


            _VS_RETURN_FORMAT.Rows.Add(dr);

            dr["field1"] = dt2.Row[0][0];
            dr["field2"] = dt2.Row[0][1];

            _VS_RETURN_FORMAT.Rows.Add(dr);

            dr["field1"] = dt1.Row[1][0];
            dr["field2"] = dt1.Row[1][1];

            _VS_RETURN_FORMAT.Rows.Add(dr);

            dr["field1"] = dt1.Row[2][0];
            dr["field2"] = dt1.Row[2][1];

            _VS_RETURN_FORMAT.Rows.Add(dr);

答案 1 :(得分:1)

select top 1 Name ClassRank from Class1 order by Score desc
union 
select top 1 Name  ClassRank from Class2 order by Score desc
union
SELECT * FROM (
  SELECT ROW_NUMBER() OVER (ORDER BY Score desc) AS rownumber    
  FROM Class1
) AS foo
WHERE rownumber >1