0

我的表结构是这样的:

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

谢谢

4

2 回答 2

1

问题出在数据中 - 您必须修复重复项。显然 1 台显示器属于 2 台 PC -
PC018 - 60P5D并且PC220 - 60P5D. 或者,您可以尝试安排它们并以某种方式将第一个 SN 用于第一台 PC,依此类推,但我认为这不是正确的方法。

于 2013-11-05T09:44:34.907 回答
0

你想如何确定你想使用哪个 sn_pc?

一个 distinct 不会解决你的问题,一个 distinct 只会消除相同的行。

如果可能,您必须聚合:min(sn_pc) 您可以在子查询中使用视图函数:row_number over (partition by sid, name_pc order by sn_pc) then where rownum = 1

但是当再次阅读结果时,似乎您在加入表格时缺少加入条件

dbo.IT_Equ AS c ON a.SID = c.SID AND c.Type = 'Monitor'

这是问题所在,如果可能,请使用子查询仅选择最后一行。

于 2013-11-05T09:44:13.633 回答