并不是来自GROUP BY的所有字段

时间:2018-01-10 15:09:03

标签: sql sql-server group-by sum aggregate-functions

我有桌子:

Id(int), 
CompanyId(uniqueidentifier), 
DateCreated(datetime), 
TypeId(int), 
Value(int), 
Date(date)

和查询:

SELECT 
    W2CliendId,
    CAST(DATEADD(month, DATEDIFF(month, 0, Date), 0) AS date) AS MonthStarts,
    CASE 
      WHEN TypeId = 1 THEN '4 Search views'
      WHEN TypeId = 2 THEN '5 Maps views'
      WHEN TypeId = 0 THEN 'Unknown'
    END AS [Type],
    SUM(Value) AS [Value]
FROM CompanyTypeValues CTV
    JOIN CompanyProfile CP
        ON CP.CompanyId = CTV.CompanyId
WHERE CP.Status = 0 AND Date >= '2015-08-11'
GROUP BY CAST(DATEADD(month, DATEDIFF(month, 0, Date), 0) AS date), TypeId, W2CliendId
ORDER BY TypeId, MonthStarts, W2CliendId

我如何SELECT仅将GROUP BY中的两个字段相加? (DATEADD(month, DATEDIFF(month, 0, Date), 0), W2CliendId

2 个答案:

答案 0 :(得分:0)

如果你只有3个类型ID(似乎是你的CASE上面的总和),解决方案可以创建三个重复大小写的列,这样你就有3个聚合结果对应于三个类型ID:

因此,在查询结束时,请替换

SUM(Value) AS [Value]

BY

SUM(CASE 
      WHEN TypeId = 1 THEN Value
      WHEN TypeId = 2 THEN 0
      WHEN TypeId = 0 THEN 0
END AS [Value_Type1],
SUM(CASE 
      WHEN TypeId = 1 THEN 0
      WHEN TypeId = 2 THEN Value
      WHEN TypeId = 0 THEN 0
END AS [Value_Type2],
SUM(CASE 
      WHEN TypeId = 1 THEN 0
      WHEN TypeId = 2 THEN 0
      WHEN TypeId = 0 THEN Value
END AS [Value_Type0],

分组依据不是为了在同一查询中的两个不同级别进行聚合。否则你可以做的是两个独立的子查询,一个在3列聚合,另一个在2列聚合,并加入两个查询。

答案 1 :(得分:0)

如果必须按所选列进行分区,请尝试使用窗口函数

SELECT   w2cliendid, 
         cast(dateadd(month, datediff(month, 0, date), 0) AS date) AS monthstarts, 
         CASE 
                  WHEN typeid = 1 THEN '4 Search views' 
                  WHEN typeid = 2 THEN '5 Maps views' 
                  WHEN typeid = 0 THEN 'Unknown' 
         END                                                                                                                                         AS [Type],
         sum(value) OVER (partion BY cast(dateadd(month, datediff(month, 0, date), 0) AS date)
         , w2cliendid ORDER BY typeid, monthstarts, w2cliendid) AS [Value] 
FROM     companytypevalues ctv 
JOIN     companyprofile cp 
ON       cp.companyid = ctv.companyid 
WHERE    cp.status = 0 
AND      date >= '2015-08-11'