带有group by子句

时间:2016-06-19 14:26:42

标签: sql-server

enter image description here

SELECT 
    MAX(srNo)         AS srNo,
    MAX(eventDesc)    AS eventDesc,
    attributeType     AS attributeType,
    MAX(companyCode)  AS companyCode,
    empCode           AS empCode,
    SUM(CAST(oldValue AS DECIMAL(10, 1))) AS oldValue,
    CASE 
       WHEN isnumeric(newValue) = 1 THEN SUM(CAST(newValue AS DECIMAL(10, 1)))
       ELSE max(newValue)
    END               AS newValue,       
    MAX(creationDate),
    createdByEmp,
    reason 
FROM   
    dummy 
GROUP BY
    creationDate, reason, createdByEmp, attributeType, empCode

我想添加newValue,如果它包含数字,则按原样显示。

此查询返回以下输出

enter image description here

请帮帮我!谢谢。

1 个答案:

答案 0 :(得分:1)

出现了什么错误?:

  

它表示你有一个名为newValue的列在虚拟关系中,应该逐个放置。

重要的是什么?

  

SELECT语句的列列表中的每个非聚合列,   其中包含至少一个聚合函数(参见SELECT语句的列),应放在其中   小组也是。

所以试试这个:

SELECT 
MAX(srNo)         AS srNo,
MAX(eventDesc)    AS eventDesc,
attributeType     AS attributeType,
MAX(companyCode)  AS companyCode,
empCode           AS empCode,
SUM(CAST(oldValue AS DECIMAL(10, 1))) AS oldValue,
CASE 
   WHEN isnumeric(newValue) = 1 THEN SUM(CAST(ISNULL(newValue,'0') AS DECIMAL(10, 1)))
   ELSE max(CAST(ISNULL(newValue,'0'))
END               AS newValue,       
MAX(creationDate),
createdByEmp,
reason 
FROM   
   dummy 
GROUP BY
creationDate, reason, createdByEmp, attributeType, empCode, newValue

最后请注意,Group BY中列的顺序很重要,因此您可能需要将newValue列放在Group By中的适当位置