我试图生成一个报告,显示哪些用户仅限于某些设施。我使用的基本代码是:
`SELECT DISTINCT ppp.DeptID,
mis.UserID,
mis.[Name],
CASE
WHEN mis.ProviderID IS NULL
THEN 'No'
ELSE 'YES'
END AS 'IsProv',
CASE
WHEN af.FacilityID = 'PSY'
THEN 'Restricted'
ELSE 'Not Restricted'
END AS 'SignOnFacility',
CASE
WHEN fr.FacilitiesRestrictedID = 'PSY'
THEN 'Restricted'
ELSE 'Not Restricted'
END AS 'FacilityToRestrict',
mis.Active
FROM DMisUsers mis
LEFT JOIN DMisUserRestrictedAdmMriFac fr
ON mis.UserID = fr.UserID
AND mis.SourceID = fr.SourceID
LEFT JOIN DMisUserAdmMriFacility af
ON af.UserID = mis.UserID
INNER JOIN PpEmployees pe
ON mis.SourceID = pe.SourceID
AND mis.UserID = pe.UserID
INNER JOIN PpPayrollPosition ppp
ON ppp.EmployeeID = pe.EmployeeID
AND pe.SourceID = ppp.SourceID
WHERE mis.SourceID = 'STP'
AND mis.Active = 'Y'`
产生以下结果集,为每个设施带来一行'列。
| DeptID | UserID |IsProv| SignOnFacility | FacilityToRestrict | Active|
|01.9030 | PPaul | No | Not Restricted | Not Restricted | Y |
|01.9030 | PPaul | No | Not Restricted | Restricted | Y |
我想要做的就是获得一行:
| DeptID | UserID |IsProv| SignOnFacility | FacilityToRestrict | Active|
|01.9030 | PPaul | No | Not Restricted | Restricted | Y |
我已经尝试过CTE,使用Row_Number()
进行聚合以及其他几种方法。任何帮助将不胜感激。
答案 0 :(得分:0)
我很确定你想要group by
。以下是我对逻辑的猜测:
SELECT ppp.DeptID, mis.UserID, mis.[Name],
COALESCE(MAX(CASE WHEN mis.ProviderID IS NOT NULL THEN 'YES' END), 'NO') as IsProv,
COALESCE(MAX(CASE WHEN af.FacilityID <> 'PSY' THEN 'Not Restricted' END), 'Restricted') as SIgnOnFacility,
COALESCE(MAX(CASE WHEN fr.FacilitiesRestrictedID <> 'PSY' THEN 'Not Restricted' END) as FacilityToRestrict,
mis.Active
FROM . . .
GROUP BY ppp.DeptID, mis.UserID, mis.[Name], mis_Active;