经理说太复杂,非要分布查询。生气。
作者:互联网
已知
tblEquipment设备表
tblRequest请求表
jctRequestEqpt请求-设备关联中间表
目的:查询根据某字段(例如部门)查询某年每月和上月请求数量,得出每月增长率,
SELECT e.DepartmentID, DATEPART(MONTH ,r1.RequestDate) AS month,COUNT(DISTINCT r1.ID) AS now,COUNT(DISTINCT r2.ID) AS pre
FROM tblRequest r1
LEFT JOIN jctRequestEqpt re ON re.RequestID =r1.ID
LEFT JOIN tblEquipment e ON e.ID =re.EquipmentID
LEFT JOIN
(
SELECT sr.ID ID,sr.RequestDate,sr.RequestType,e.DepartmentID
FROM tblEquipment e
LEFT JOIN jctRequestEqpt sre ON sre.EquipmentID = e.ID
LEFT JOIN tblRequest sr ON sr.ID =sre.RequestID
) r2
ON r1.RequestType =r2.RequestType
AND DATEPART(MONTH,r1.RequestDate) = DATEPART(MONTH ,r2.RequestDate)+1
AND DATEPART(YEAR,r1.RequestDate) = DATEPART(YEAR ,r2.RequestDate)
AND r2.DepartmentID =e.DepartmentID
WHERE r1.RequestType=1 AND DATEPART(YEAR,r1.RequestDate)=2019 AND re.RequestID IS NOT NULL AND re.EquipmentID IS NOT NULL
GROUP BY DATEPART(MONTH ,r1.RequestDate) ,e.DepartmentID
得到数据:
经理看到后,说太复杂,以后别人维护起来不太好整,用分步查询,先查一个月 再查上一个月,得到数据后,进行匹配再封装。
我就*了*了,哪里复杂了,三个join,一个临时表的分组查询,
一个查询就得到目标数据了,为什么要分开查 ,再去循环封装。
太阳!!
标签:DATEPART,JOIN,r1,r2,经理,生气,查询,RequestDate,ID 来源: https://blog.csdn.net/qq_43016856/article/details/98942242