0

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
2
  • You are close try Using Count() with current query for ex. SUM(CASE WHEN .....<your condition> as NEW_ACCOUNTS), SUM(CASE WHEN ....<condition flip for old records> as OLD_ACCOUNTS that should do it. Commented Jul 16, 2019 at 10:44
  • Did you try DISTINCT in your query ? Commented Jul 16, 2019 at 10:54

2 Answers 2

1

I think you want conditional aggregation:

SELECT REP,
       SUM(CASE WHEN YEAR(GETDATE()) = YEAR(DATE_CREATED) THEN 1 ELSE 0 END) AS NEW_ACCOUNTS,
       SUM(CASE WHEN YEAR(GETDATE()) > YEAR(DATE_CREATED) THEN 1 ELSE 0 END) AS OLD_ACCOUNTS,
       COUNT(*) as TOTAL
FROM CUSTOMERS
GROUP BY REP;

This assumes that creation dates are not in the future -- a reasonable assumption.

If you want one row per REP, then the only column in the GROUP BY should be REP.

Sign up to request clarification or add additional context in comments.

Comments

1

You can want conditional aggregation :

SELECT REP, 
       SUM(CASE WHEN YEAR(GETDATE()) = YEAR(DATE_CREATED) THEN 1 ELSE 0 END) AS NEW_ACCOUNTS,            
       SUM(CASE WHEN YEAR(GETDATE()) > YEAR(DATE_CREATED) THEN 1 ELSE 0 END) AS OLD_ACCOUNTS, COUNT(*) AS TOTAL       
FROM CUSTOMERS
GROUP BY REP;

1 Comment

use this condition YEAR(GETDATE()) > YEAR(DATE_CREATED), If use '<' it gives 0 result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.