SQL Server-获取去年平均值,当年每月平均值和当年总计平均值

时间:2019-02-19 20:25:10

标签: sql sql-server

我正在SQL Server中运行一个简单查询,以获取按月分组的当前年平均值,因此它返回12行。我需要在第一行中输入去年的TOTAL平均值,在最后一行中输入当前年的TOTAL平均值,因此它将变成14行。

current result

这是我的查询:

SELECT 
    COUNT(*) AS mes 
FROM 
    WorkOrder 
WHERE 
    workOrderSource = '02'  
    AND YEAR(workOrderDate) = 2018 
    AND conclusionDate IS NULL 
GROUP BY 
    MONTH(workOrderDate);

我应该如何传递动态年份,并在查询中添加2条额外的行以及过去和当前年份的总和?

结果应该有14行; “第一行”是去年的TOTAL平均值,“最后一行”是今年的TOTAL平均值

1 个答案:

答案 0 :(得分:1)

以这种方式尝试:

  SELECT COUNT(*) AS mes, null
    FROM WorkOrder 
    WHERE workOrderSource = '02'  
      AND YEAR(workOrderDate) = 2018
      AND conclusionDate IS NULL 
    UNION ALL 
    SELECT COUNT(*), MONTH(workOrderDate)
    FROM WorkOrder 
    WHERE workOrderSource = '02' 
      AND YEAR(workOrderDate) = 2019
      AND conclusionDate IS NULL 
    GROUP BY ROLLUP(MONTH(workOrderDate))
    ORDER BY COALESCE(MONTH(workOrderDate), 13)