有没有一种方法可以按年份划分sql结果?

时间:2020-01-09 17:42:51

标签: sql sql-server group-by count pivot

我目前有以下SQL语句:

public order(data) {
    const order = data.externalOrderId;
    if (order.substring(0, 4) === 'asdad') {
      return true;
    } else {
      return false;
    }
  }


 public isFree$ = this.planType$.pipe(
    map((data) => {
      return (data.plan === 'Free');
    }
));

目前,每个管理者都会吐出全部项目。我想让它按项目完成的年数划分项目。因此,基本上可以计算出每个经理(每年(2016、2017等)的总项目数)以及所有时间的总项目数。我可以将SELECT [Manager].[Name], COUNT([Project].[ProjectId]) AS TotalProjects FROM ([Project] INNER JOIN [Manager] ON [Project].[ManagerId] = [Manager].[ManagerId]) WHERE [Project].[CurrentStatusId] = 5 GROUP BY [Manager].[Name] 列用作日期。

1 个答案:

答案 0 :(得分:6)

只需将项目年份添加到SELECTGROUP BY子句中即可:

SELECT
    [Manager].[Name], 
    YEAR([Project].[CurrentStatusDt]) PojectYear,
    COUNT([Project].[ProjectId]) AS TotalProjects
FROM [Project]
INNER JOIN [Manager] ON [Project].[ManagerId] = [Manager].[ManagerId]
WHERE [Project].[CurrentStatusId] = 5
GROUP BY [Manager].[Name], YEAR([Project].[CurrentStatusDt])

侧面说明:在SQL Server中,连接时不需要括号(这是MS Access的限制)。


编辑

如果您想将年份分布在列而不是行上,那么一种解决方案是使用条件聚合

SELECT
    [Manager].[Name], 
    SUM(CASE 
        WHEN [Project].[CurrentStatusDt] < CAST('2019-01-01' AS DATE)
        THEN 1 
        ELSE 0 
    END) TotalProjects2018,
    SUM(CASE 
        WHEN [Project].[CurrentStatusDt] >= CAST('2019-01-01' AS DATE)
        THEN 1 
        ELSE 0 
    END) TotalProjects2019
FROM [Project]
INNER JOIN [Manager] ON [Project].[ManagerId] = [Manager].[ManagerId]
WHERE 
    [Project].[CurrentStatusId] = 5 
    AND [Project].[CurrentStatusDt] >= CAST('2018-01-01' AS DATE)
    AND [Project].[CurrentStatusDt] <  CAST('2020-01-01' AS DATE)
GROUP BY [Manager].[Name]