我的表中的一个列是varchar类型。其中包含十六进制值。 我需要取特定月份的平均值。 以下是我的查询。请帮助我如何更改代码来实现它。
select avg(hex) from history where Date between '2016-11-01' and '2017-11-29' group by Date;
提前致谢
答案 0 :(得分:1)
您可以CAST
使用DateTime
SqlCommand command = new SqlCommand("SELECT Top 1 CAST(TimeStamp AS DATETIME) as TimeStamp FROM HistoryReport ", conn);
例如
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);
}
}