如何在SQL中的子选定列上执行GROUP BY

时间:2019-01-25 18:27:45

标签: sql

例如,我正在执行以下查询:

SELECT 
   W.UserID, 
   W.Number,
   (SELECT StatusDate FROM WStatuses AS WS WHERE WS.Number = W.NUmber AND WS.StatusType = 'CRFI') AS StatusDate
   W.Model
FROM WorkOrder AS W

GROUP BY MONTH(StatusDate)

我该如何举止?有一个WORKORDER表和一个WORKORDERSTATUS表。 WORKORDER表的每个工单号都有一个条目。 WORKORDERSTATUS表具有该工作单编号的所有WORKORDERSTATUS更改的历史记录。因此,我仅将状态更改为CRFI的日期拉。然后,我需要按返回的那列中的月份进行分组,并说这不是有效的列。任何帮助将不胜感激,并祝您编程愉快!

2 个答案:

答案 0 :(得分:2)

您可以使用子查询方法

SELECT MONTH(StatusDate), sum(w.Number) num
FROM
(
  SELECT 
     W.UserID, 
     W.Number,
     (SELECT StatusDate FROM WStatuses AS WS WHERE WS.Number = W.NUmber AND WS.StatusType = 'CRFI') AS StatusDate
     W.Model
  FROM WorkOrder AS W
) T
GROUP BY MONTH(StatusDate)

替代方法(如果您确定只有状态为W CRFI的WStatuses将返回一条记录)

SELECT 
   avg(W.Number),
   MONTH(StatusDate)
FROM WorkOrder AS W
INNER JOIN Wstatuses 
  on WS.Number = W.NUmber AND WS.StatusType = 'CRFI'
GROUP BY MONTH(StatusDate)

答案 1 :(得分:0)

请考虑避免使用相关子查询(为行计算一次),以获得更高效的JOIN。另外,将SELECT子句中列出的所有非聚合列都包含在GROUP BY子句中,这是对ANSI标准运行聚合查询的一种正确方法。并运行所需的汇总,如下调整所示。

SELECT 
   W.UserID, 
   W.Number,
   MONTH(S.StatusDate) AS StatusMonth
   W.Model,
   COUNT(...) AS CountAgg,
   SUM(...) AS SumAgg,
   AVG(...) AS AvgAgg,
   ...
FROM WorkOrder AS W
INNER JOIN WStatuses AS S
  ON S.Number = W.NUmber AND S.StatusType = 'CRFI'

GROUP BY W.UserID, 
         W.Number,      
         MONTH(S.StatusDate)
         W.Model