简体   繁体   中英

C# SQL Date Range

I am strugling with a sql select query for my MVC Web Application. I have a datetime field in my local db, and I want to query all the customers that have created an appointment in the first semester, or the second semester of the year.

Something like this:

Select Count( all the appointments until '01/06/2020') as FirstSemester,
Count(all the appointments from '01/06/2020' until '31/12/2020) as SecondSemester

PS: I want to have two counts, because with those values I am going to create a chart to illustrate the system evolution(how many clients in the first semester vs second semester).

Does this kind of query exist? And if the answer is yes, how would it look like?

Thank you so much!

You would typically use conditional aggregation:

select
    sum(case when mydate < date '2020-07-01' then 1 else 0 end) first_semester,
    sum(case when mydate >= date '2020-01-07' then 1 else 0 end) second_semester
from mytable
where mydate >= date '2020-01-01' and mydate < date '2021-01-01'

The actual syntax for date literals may vary across databases. The above query uses standard ANSI SQL syntax.

Side note: I would assume that the second semester starts in July rather than June.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM