I'm trying to query a customers table to get the total number of accounts per rep grouped by whether they were created this year or before.
- CUSTOMER NAME
- ACCOUNT REP
- DATE CREATED
The query I'm trying to return would look like.
REP | NEW_ACCOUNTS | OLD_ACCOUNTS | TOTAL
-----------------------------------------
Tom | 100 | 12 | 112
Ted | 15 | 1 | 16
The query I've written looks as follows.
SELECT REP, CASE WHEN YEAR(GETDATE()) > YEAR(DATE_CREATED) THEN 1 ELSE 0 END AS ThisYear
FROM CUSTOMERS
GROUP BY REP, DATE_CREATED
Unfortunately, this is giving me
REP | ThisYear
-----------------------------------------
Tom | 1
Ted | 0
Tom | 0
Ted | 1
Ted | 1
Count()with current query for ex.SUM(CASE WHEN .....<your condition> as NEW_ACCOUNTS), SUM(CASE WHEN ....<condition flip for old records> as OLD_ACCOUNTSthat should do it.