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