使用Group by进行MSSQL连接查询

时间:2013-11-05 09:00:48

标签: sql sql-server join group-by left-join

我的表结构如下:

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

我想创建一个VIEW来按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

如果staf只有一条PC和显示器记录,代码工作正常,它将显示以下结果:

SID Name_PC SN_PC   Name_Monitor    SN_Monitor  DisplayName
372 XX      1234ZZ  YYY             2234ZZ      Peter   
444 BBB     2255XX  CCC             4512XC      John

但如果员工有多个PC记录或监控记录,则会创建重复记录,例如

db中的原始记录:

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

感谢

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

如何确定要使用哪个sn_pc?

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

如果可能,你必须聚合:min(sn_pc) 您可以在子查询中使用视图函数:row_number over(sid分区,name_pc按sn_pc顺序),然​​后rownum = 1

但是当再次阅读结果时,您似乎在加入表格时缺少连接标准

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

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