按年份排序,无论年份或月份

时间:2013-08-17 13:45:08

标签: c# sql isqlquery

你好,我有一个问题,我希望通过按日排序来显示日期,现在首先是生日,例如:我有

15/08/2013 00:00:00
15/08/2013 00:00:00
29/08/2012 00:00:00
23/08/2012 00:00:00
16/08/2012 00:00:00
10/08/2012 00:00:00

我希望它是

10/08/2012 00:00:00
15/08/2013 00:00:00
15/08/2013 00:00:00
16/08/2012 00:00:00
23/08/2012 00:00:00
29/08/2012 00:00:00

我写道:

public DataTable BirtdayReport(DateTime d)
{
    try
    {

        string query = "SELECT C.Class_Name as [כיתה], P.Person_First_Name as [שם פרטי], P.Person_Last_Name as [שם משפחה], P.Date_Of_Birth AS [תאריך לידה] ";
        query += "FROM Person as P INNER JOIN Customer as C ON P.[Person _ID] = C.Person_ID WHERE MONTH(P.Date_Of_Birth)=Month(@d) ORDER BY (DAYOFMONTH(Person.Date_Of_Birth)) ;";

        OleDbCommand command = new OleDbCommand();
        command.CommandText = query;
        command.Parameters.AddWithValue("@d", d);
        DataTable dt = AdoHelper.ExecuteDataTable(command);
        return dt;

    }
    catch (Exception ex)
    {
        throw ex;
    }
}

但它并不像我想要的那样排序。 你能救我吗?

2 个答案:

答案 0 :(得分:0)

select 
    col1, col2, col3, col4
from
(
SELECT 
    C.Class_Name as col1, 
    P.Person_First_Name as col2, 
    P.Person_Last_Name as col3, 
    P.Date_Of_Birth AS col4,
    DAYOFMONTH(Person.Date_Of_Birth) as ordCol
FROM 
    Person as P INNER JOIN 
    Customer as C 
        ON P.[Person _ID] = C.Person_ID 
WHERE 
    MONTH(P.Date_Of_Birth)=Month(@d) 
) tbl
ORDER BY tbl.ordCol

答案 1 :(得分:0)

这是基于标准SQL,但应该很容易根据您的SQL方言修改它:

ORDER BY 
   CASE WHEN EXTRACT(MONTH FROM Date_Of_Birth) > EXTRACT(MONTH FROM CURRENT_DATE) 
         OR (EXTRACT(MONTH FROM Date_Of_Birth) = EXTRACT(MONTH FROM CURRENT_DATE) AND 
             EXTRACT(  DAY FROM Date_Of_Birth)>= EXTRACT(DAY   FROM CURRENT_DATE))
        THEN 0 
        ELSE 1
   END,
   EXTRACT(MONTH FROM Date_Of_Birth), EXTRACT(DAY FROM Date_Of_Birth)