0

我正在使用 SQL Server 2008

我有 2 张桌子

  1. 附言

    列:PS_ID(PK)、AID(FK)、PS_Vendor

  2. 系统

    列:System_ID(PK)、AID(FK)、Sys_Prod

这两个表通过连接PS.AID = System.AID

我必须找到每个的计数和PS_Vendors每个SYS_Product的总数Sys_product

我的输出必须看起来像:

PS_Vendor Sys_product Count Total
 ABC         A         2      10  
 ABC         B         5      20       
 ABC         C         0      15
 XYZ         A         3      10
 XYZ         B         0      20
 XYZ         C         12     15 

我创建了一个名为PS_system_View

select * from system
left outer join ps
on ps.aid=system.aid

我无法结合这些

select B.ps_vendor, A.sys_product, B.Count,A.Total from 

--To get the total:

select sys_product, sum(total) as Total from

(select sys_product, ps_vendor, sum(case when sys_product is not null then 1 else 0 end) as total

 from PS_System_view

)A

group by sys_product

left join

(

--To get the count:

select sys_product, ps_vendor, sum(case when ps_vendor is not null then 1 else 0 end) as count from
 PS_System_view

where ps_vendor is not null and sys_product is not null

)B on B.sys_product=A.Sys_product
4

0 回答 0