我有一个这样的表,在后面的代码中,我必须在标签中显示tempname,在下拉列表中显示rundate,我必须在下拉列表中显示最后10个rundate,没有重复的名称我的意思是我必须显示唯一DDL中的tempname和关联的rund。我可以实现这个吗?我需要一个存储过程。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dt = new DataTable();
dt = Common.rundate();
DropDownList ddl = e.Row.FindControl("DropDownList1") as DropDownList;
ddl.DataTextField = "RunDate";
ddl.DataValueField = "TempID";
ddl.DataSource = dt;
ddl.DataBind();
}
}
public static DataTable rundate()
{
DBAccess objDBAccess = new DBAccess();
DataTable dt = new DataTable();
try
{
objDBAccess.AddParameter("@tempname", SqlDbType.VarChar);
objDBAccess.AddParameter("@tempid", SqlDbType.Int);
objDBAccess.AddParameter("@rundate", SqlDbType.DateTime);
dt = objDBAccess.ExecuteDataTable("display_rundates");
return dt;
}
catch
{
return null;
}
}
答案 0 :(得分:0)
尝试此查询:
SELECT
TOP 10
MAX(RunDate) RunDate
, TempName
From
tblTest
GROUP BY
TempName
ORDER BY
RunDate DESC
如果你需要获得TempID,那么试试这个(假设TempID是标识列):
;WITH cteDllLastRun AS (
SELECT
MAX(TempID) TempID
,TempName
FROM
tblTest
GROUP BY
TempName
)
SELECT
TOP 10
tblTest.*
FROM
cteDllLastRun
INNER JOIN
tblTest
ON
tblTest.TempID = cteDllLastRun.TempID
ORDER BY
tblTest.RunDate DESC
如果tempID不唯一,则查询该案例:
;WITH cteDlls AS (
SELECT
DISTINCT
TempName
FROM
tblTest
)
SELECT
TOP 10
vwLastRun.*
FROM
cteDlls
CROSS APPLY
(
SELECT TOP 1
*
FROM
tblTest
WHERE
tblTest.TempName = cteDlls.TempName
ORDER BY
RunDate DESC
) vwLastRun
ORDER BY
RunDate DESC
对于最后一个解决方案,您需要确保将TempName和RunDate编入索引,以便获得适当的性能。