如何取Varchar数据类型的平均值

时间:2018-03-06 09:35:49

标签: sql

我的表中的一个列是varchar类型。其中包含十六进制值。 我需要取特定月份的平均值。 以下是我的查询。请帮助我如何更改代码来实现它。

select avg(hex) from history where Date between '2016-11-01' and '2017-11-29' group by Date;  

提前致谢

1 个答案:

答案 0 :(得分:1)

您可以CAST使用DateTime

 SqlCommand command = new SqlCommand("SELECT Top 1 CAST(TimeStamp AS DATETIME) as TimeStamp  FROM HistoryReport ", conn);

CAST

例如

SELECT CAST('2017/10/10' AS DATETIME)

该字段应为DateTime字符串,否则将为错误

修改

一个小例子。

keyPoint是command.ExecuteReader()获取SQL查询集合。

string commandText = "SELECT Top 1 CAST(TimeStamp AS DATETIME) as TimeStamp  FROM HistoryReport ";
string connectionString = "your Connection string";
using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(commandText, conn);
    try
    {
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            DateTime date = reader[0] as DateTime;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

SqlCommand