Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

c# - Counting the number of rows in an SQLite database for this week

I have the following query that returns the count of books entered in the last 7 days. Is it possible to modify the query so that it only returns the count of those entered since the start of the week?

public int GetWeeklyCount()
 {
       var week = DateTime.Today.AddDays(-7);
       return database.ExecuteScalar<int>("SELECT count(*) FROM Book WHERE bookEntryTime > ?;", week);
 }
question from:https://stackoverflow.com/questions/65946915/counting-the-number-of-rows-in-an-sqlite-database-for-this-week

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

People vary as to what they mean by the start of a week, but for example if you think a week starts on Monday:

var week = DateTime.Today;
while(week.DayOfWeek != DayOfWeek.Monday)
    week = week.AddDays(-1);
return database.ExecuteScalar<int>("SELECT count(*) FROM Book WHERE bookEntryTime > ?;", week);

You could also straight to the math:

var week = DateTime.Today.AddDays(-(((int)DateTime.Today.DayOfWeek+6)%7));
return database.ExecuteScalar<int>("SELECT count(*) FROM Book WHERE bookEntryTime > ?;", week);

But to me it's relatively non-self-documenting for little performance advantage


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...