-2

I have database and one birthday field with date type. I have to find average age, max age and min age abouth their birthday in c#. Can you help me?

4

2 に答える 2

1

日付と時刻の関数は、データベースに固有です。以下は、SQL Server でこれを行う方法を示しています。

select avg(cast(datediff(year, birthdate, getdate()) as float)) as avg_age,
       min(datediff(year, birthdate, getdate())) as min_age,
       max(datediff(year, birthdate, getdate())) as max_age

すべてのデータベースは同様の機能を持っていますが、名前や構文が多少異なる場合があります。これcast( . . . to float)は、SQL Server が整数値の整数平均を行うためです。一部のデータベースは、キャストなしで浮動小数点平均を生成します。

、、など、getdate()データベースによっても機能が異なります。now()sysdate()CURRENT_DATETIME

于 2013-06-08T14:49:51.163 に答える
0

次の SQL クエリを使用する必要があります。

SELECT MIN(age_columnName) FROM TableName;

SELECT MAX(age_columnName) FROM TableName;

SELECT AVG(age_columnName) FROM TableName;

次のように、C# コードでこれらのクエリを使用する必要があります。

using System.Data.SqlClient;
//
    // First access the connection string, which may be autogenerated in Visual Studio for you.
    //
    string connectionString = "connection string"
    //
    // In a using statement, acquire the SqlConnection as a resource.
    //
    using (SqlConnection con = new SqlConnection(connectionString))
    {
        //
        // Open the SqlConnection.
        //
        con.Open();
        //
        // The following code shows how you can use an SqlCommand based on the SqlConnection.
        //
        using (SqlCommand command = new SqlCommand("SELECT AVG(age_columnName) FROM TableName", con))
        using (SqlDataReader reader = command.ExecuteReader())
        {
        while (reader.Read())
        {
            // process it
        }
        }
    }
于 2013-06-08T12:27:15.400 に答える