GROUP BY带重复项,但不分组

时间:2019-11-22 10:45:35

标签: sql sql-server group-by common-table-expression

我正在尝试按日期和Off / OnStreet连续GROUP BY的每个授权ID。我不了解SQL查询中出了什么问题。它带给我重复的或重复的AuthorityId,而不是根据日期和On / Offstreet上的权限ID对所有内容进行分组。

enter image description here

这是我的SQL查询

WITH ParkeonCTE
AS
(
SELECT 
    OccDate = CONVERT(DATE, LocalStartTime),
    TotalOccSessions = COUNT(SessionId),
    AuthorityId,
    (CASE
        WHEN OC.OspId IS NULL THEN 'OffStreet' ELSE 'OnStreet'
        END
    ) AS ParkingContextType
FROM Analytics.OccupancySessions AS OC
WHERE AuthorityId IS NOT NULL
GROUP BY  CONVERT(DATE,LocalStartTime), AuthorityId, OspId
)

  SELECT CONVERT(DATE,OC.OccDate),
   OC.TotalOccSessions,
   OC.ParkingContextType,
    OC.AuthorityId
  FROM ParkeonCTE AS OC
  GROUP BY CONVERT(DATE, OC.OccDate), OC.AuthorityId, OC.TotalOccSessions, OC.ParkingContextType
  ORDER BY CONVERT(DATE,OC.OccDate) DESC

2 个答案:

答案 0 :(得分:1)

外部查询对1个分组过多。

...
SELECT 
 CONVERT(DATE,OC.OccDate) AS OccDate,
 SUM(OC.TotalOccSessions) AS TotalOccSessions,
 OC.ParkingContextType,
 OC.AuthorityId
FROM ParkeonCTE AS OC
GROUP BY CONVERT(DATE, OC.OccDate), OC.AuthorityId, OC.ParkingContextType
ORDER BY CONVERT(DATE, OC.OccDate) DESC

答案 1 :(得分:1)

使用汇总函数SUM()

WITH ParkeonCTE
AS
(
SELECT 
    OccDate = CONVERT(DATE, LocalStartTime),
    TotalOccSessions = COUNT(SessionId),
    AuthorityId,
    (CASE
        WHEN OC.OspId IS NULL THEN 'OffStreet' ELSE 'OnStreet'
        END
    ) AS ParkingContextType
FROM Analytics.OccupancySessions AS OC
WHERE AuthorityId IS NOT NULL
GROUP BY  CONVERT(DATE,LocalStartTime), AuthorityId, OspId
)

   SELECT 
      CONVERT(DATE,OC.OccDate),
      SUM(OC.TotalOccSessions),
      OC.ParkingContextType,
      OC.AuthorityId
  FROM ParkeonCTE AS OC
  GROUP BY CONVERT(DATE, OC.OccDate), OC.AuthorityId, OC.ParkingContextType
  ORDER BY CONVERT(DATE,OC.OccDate) DESC