在总和内计数时无效使用按功能分组

时间:2018-09-12 14:53:28

标签: mysql group-by sum mariadb

我有下一个查询:

select H.UserID, N.LocatieID, N.Norm * COUNT(DISTINCT DATE(H.Starttijd)) AS 
Norm FROM Locatienorm N LEFT JOIN Uur H ON N.LocatieID = H.LocatieID GROUP BY 
H.UserID, N.LocatieID, N.Norm

它给了我下一个结果

enter image description here

我想得到结果:

6 1 0.56

6 4 0.96

但是当我总结标准时,我得到了错误:

  

无效使用按功能分组

像这样:

select H.UserID, 
       N.LocatieID, 
       SUM(N.Norm * COUNT(DISTINCT DATE(H.Starttijd))) AS 
Norm 
FROM Locatienorm N 
LEFT JOIN Uur H ON N.LocatieID = H.LocatieID 
GROUP BY 
H.UserID, N.LocatieID, N.Norm

我做错了还是不支持?

服务器版本:10.1.31 MariaDB服务器

2 个答案:

答案 0 :(得分:1)

您不能嵌套组功能。试一试-

SELECT H.UserID
      ,N.LocatieID
      ,SUM(Norm)
FROM ( SELECT H.UserID
             ,N.LocatieID
             ,N.Norm * COUNT(DISTINCT DATE(H.Starttijd)) AS Norm 
       FROM Locatienorm N
       LEFT JOIN Uur H ON N.LocatieID = H.LocatieID
       GROUP BY H.UserID, N.LocatieID) A
GROUP BY H.UserID
        ,N.LocatieID

答案 1 :(得分:0)

像这样的嵌套聚合功能将不起作用。但是您可以在子查询中进行汇总,然后在外部查询中对结果进行汇总。

示例:

SELECT H.UserID, N.LocatieID, 
SUM(N.Norm * H.TotalDays) AS Norm 
FROM Locatienorm AS N
LEFT JOIN (
   SELECT
    LocatieID, UserID, 
    COUNT(DISTINCT DATE(Starttijd)) AS TotalDays 
   FROM Uur
   GROUP BY LocatieID, UserID
) AS H ON N.LocatieID = H.LocatieID
GROUP BY N.LocatieID, H.UserID

您可以在妊娠here上对其进行测试