我的表结构是这样的:
ID SID Type Description SN
82 372 PC XX 1234ZZ
83 372 Monitor YYY 2234ZZ
587 444 PC BBB 2255XX
588 444 Monitor CCC 4512XC
我想创建一个视图以按 SID(员工 ID)显示同一行组中的所有记录
我的sql如下:
SELECT DISTINCT a.SID,
CAST(b.Description AS NVARCHAR(100)) AS Name_PC,
CAST(b.SN AS NVARCHAR(100)) AS SN_PC,
CAST(c.Description AS NVARCHAR(100)) AS Name_Monitor,
CAST(c.SN AS NVARCHAR(100)) AS SN_Monitor,
dbo.StaffDB.DisplayName
FROM dbo.IT_Equ AS a INNER JOIN
dbo.StaffDB ON a.SID = dbo.StaffDB.SID LEFT OUTER JOIN
dbo.IT_Equ AS b ON a.SID = b.SID AND b.Type = 'PC' LEFT OUTER JOIN
dbo.IT_Equ AS c ON a.SID = c.SID AND c.Type = 'Monitor'
WHERE (b.Description IS NOT NULL) AND (b.SN IS NOT NULL)
AND (c.Description IS NOT NULL) AND (c.SN IS NOT NULL)
GROUP BY a.SID, CAST(b.Description AS NVARCHAR(100)),
CAST(b.SN AS NVARCHAR(100)),
CAST(c.Description AS NVARCHAR(100)),
CAST(c.SN AS NVARCHAR(100)),
StaffDB.DisplayName
如果工作人员只有一条 PC 和显示器记录,则代码可以正常工作,它将显示以下结果:
SID Name_PC SN_PC Name_Monitor SN_Monitor DisplayName
372 XX 1234ZZ YYY 2234ZZ Peter
444 BBB 2255XX CCC 4512XC John
但如果员工有多个 PC 记录或监控记录,则会创建重复记录,例如
数据库中的原始记录:
ID SID Type Description SN
106 476 PC PC018 84TK5
107 476 Monitor LCD018 60P5D
421 476 PC PC220 85HYC
422 476 Monitor LCD220 51RMR
结果是这样的:
SID Name_PC SN_PC Name_Monitor SN_Monitor DisplayName
476 PC018 84TK5 LCD018 60P5D Mary
476 PC018 84TK5 LCD220 51RMR Mary
476 PC220 85HYC LCD018 60P5D Mary
476 PC220 85HYC LCD220 51RMR Mary
是否可以将查询增强为这个?
SID Name_PC SN_PC Name_Monitor SN_Monitor DisplayName
476 PC018 84TK5 LCD018 60P5D Mary
476 PC220 85HYC LCD220 51RMR Mary
谢谢