想請問為何我得出的資料差這麼多,確認SQL command都是一樣的,可是得到的結果不一樣
//SSMS
SELECT id, username, postdate, views FROM Book_table
//查詢結果
//id(int),username(nvarchat),postdate(datetime),views(int)
//1,Juro,2023-02-06 00:00:00.000,125
//2,Juro,2023-02-06 00:00:00.000,125
//3,Juro,2023-03-06 00:00:00.000,125
//4,Juro,2023-03-06 00:00:00.000,125
SELECT username, SUM(views) as views FROM Book_table WHERE datepart(month, postdate) = 2 AND datepart(year, postdate) = 2023 GROUP BY username order by views desc
//查詢結果
//username(nvarchat),views(int)
//Juro,250
//C#
public List<Book_top> GetBook_Top()
{
List<Book_top> BItems = new List<Book_top>();
SqlConnection sqlConnection = new SqlConnection(Resources.SqlConnectionString);
SqlCommand sqlCommand = new SqlCommand($"SELECT username, SUM(views) as views FROM Book_table WHERE datepart(month, postdate) = {DateTime.Now.Month} AND datepart(year, postdate) = {DateTime.Now.Year} GROUP BY username order by views desc");
sqlCommand.Connection = sqlConnection;
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Book_top list = new Book_top
{
username = reader.GetString(reader.GetOrdinal("username")),
views = reader.GetInt32(reader.GetOrdinal("views"))
};
BItems.Add(list);
}
}
sqlConnection.Close();
return BItems;
}
//查詢結果
[0]=Juro125
[1]=Juro125
[2]=Juro125
[3]=Juro125
SSMS
//SSMS
SELECT
id, username, postdate, views
FROM Book_table
SELECT
username, SUM(views) as views
FROM table_name
WHERE datepart(month, postdate) = 2 AND datepart(year, postdate) = 2023
GROUP BY username order by views desc
請問是 table_name ? 還是 Book_table ?
提供一個DEBUG的方法
您可以將C#程式碼中的SqlCommand語句內容印出來
等你印出來後....可以貼到SSMS執行看看結果
您可以對比一下到底你的SQL語句和您執行的SQL語句是否相同,以確定是否存在任何差異。
public List<Book_top> GetBook_Top()
{
List<Book_top> BItems = new List<Book_top>();
SqlConnection sqlConnection = new SqlConnection(Resources.SqlConnectionString);
SqlCommand sqlCommand = new SqlCommand($"SELECT username, SUM(views) as views FROM Book_table WHERE datepart(month, postdate) = {DateTime.Now.Month} AND datepart(year, postdate) = {DateTime.Now.Year} GROUP BY username order by views desc");
sqlCommand.Connection = sqlConnection;
//印出來
Console.WriteLine("SQL Command: " + sqlCommand.CommandText);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Book_top list = new Book_top
{
username = reader.GetString(reader.GetOrdinal("username")),
views = reader.GetInt32(reader.GetOrdinal("views"))
};
BItems.Add(list);
}
}
sqlConnection.Close();
return BItems;
}