SQL查询每个记录的两个值

时间:2019-07-16 10:40:30

标签: sql sql-server

我正在尝试查询客户表,以获取每个代表的帐户总数(按它们是在今年还是之前创建的分组)。

  • 客户名称
  • 帐户代表
  • 创建日期

我要返回的查询看起来像这样。

REP | NEW_ACCOUNTS | OLD_ACCOUNTS | TOTAL
-----------------------------------------
Tom | 100          | 12           | 112
Ted | 15           | 1            | 16

我编写的查询如下。

SELECT        REP, CASE WHEN YEAR(GETDATE()) > YEAR(DATE_CREATED) THEN 1 ELSE 0 END AS ThisYear
FROM          CUSTOMERS
GROUP BY      REP, DATE_CREATED

不幸的是,这给了我

REP | ThisYear
-----------------------------------------
Tom | 1
Ted | 0
Tom | 0
Ted | 1
Ted | 1

2 个答案:

答案 0 :(得分:1)

我认为您需要条件聚合:

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;

这是假设创建日期不在将来,这是一个合理的假设。

如果您希望每REP行,那么GROUP BY中的唯一列应为REP

答案 1 :(得分:1)

您可能需要条件聚合:

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;