就上下文而言,我从事交通工作。另外,我为一个糟糕的头衔道歉 - 我不确定如何总结我的问题。
我目前正在编辑一份现有的报告,该报告会返回一个驱动程序ID,他们的名字,他们被雇用的时间,以及他们从公司开始以来的总里程数。引起我注意的是,在公司内部移动的司机被分配了一个不同的驾驶员ID,而不计入他们驾驶的总里程数。使用提供给我的示例,我确实能够确认这种情况,如下所示:
DriverCode DriverName
----------- ----------------
WETDE Wethington,Dean
WETDEA Wethington,Dean
这是获得上述内容的查询(示例驱动程序目前是硬编码的):
select mpp.mpp_id as DriverCode,
mpp.mpp_lastfirst as DriverName
from manpowerprofile mpp
outer apply (select top 1 mpp_id
from manpowerprofile) as id
where mpp_firstname = 'Dean'
and mpp_lastname = 'Wethington'
这是当前的查询:
SELECT lh.lgh_driver1 as DriverCode
,m.mpp_lastfirst as DriverName
,m.mpp_hiredate as HireDate
,SUM(s.stp_lgh_mileage) as TotMiles
FROM stops s (nolock)
INNER JOIN legheader lh (nolock) on lh.lgh_number = s.lgh_number
INNER JOIN manpowerprofile m (nolock) on m.mpp_id = lh.lgh_driver1
/* OUTER APPLY ( SELECT top 1 mpp_id
FROM manpowerprofile) as id */
WHERE m.mpp_terminationdt > GETDATE()
AND m.mpp_id <> 'UNKNOWN'
AND lh.lgh_outstatus = 'CMP'
GROUP BY lh.lgh_driver1, m.mpp_lastfirst, m.mpp_hiredate
HAVING SUM(s.stp_lgh_mileage) > 850000
ORDER BY DriverCode DESC
我要做的是检查名称是否存在两次,如果存在,则将这两个驱动程序代码的总里程相加,以返回单个驱动程序的单个结果。我仍然是SQL开发人员的新手,现在才真正开始深入研究数据库。
我目前的思路是使用外部应用,但我确信有更好的方法来做到这一点。
答案 0 :(得分:1)
根据你的评论,不用驱动程序代码和雇用日期...... (因为他们可能/将会被合并的驱动程序不同。)
SELECT
m.mpp_lastfirst as DriverName
,SUM(s.stp_lgh_mileage) as TotMiles
FROM
stops s (nolock)
INNER JOIN
legheader lh (nolock)
on lh.lgh_number = s.lgh_number
INNER JOIN
manpowerprofile m (nolock)
on m.mpp_id = lh.lgh_driver1
WHERE
m.mpp_terminationdt > GETDATE()
AND m.mpp_id <> 'UNKNOWN'
AND lh.lgh_outstatus = 'CMP'
GROUP BY
m.mpp_lastfirst
HAVING
SUM(s.stp_lgh_mileage) > 850000
ORDER BY
m.mpp_lastfirstDESC