SQL Server - Group by返回相同的信息

时间:2017-12-22 15:02:57

标签: sql stored-procedures grouping

我习惯于MySQL如何与Group_Concat一起使用,因此难以理解SQL服务器如何使用组连接。由于我选择PPNumber值,因此我无法仅xml pathBx分组进行分组。

有没有办法根据pp.[PPNumber] as PartNumber列制作Bx值组的分隔列表,或者是否有更好的方法让Bxs仅在PPNumber列内进行分组xml path分组?

SELECT  
pp.[PPNumber]  as PartNumber,
COUNT(PSN) as ActualCount, 
replace((SELECT b.Bx AS [data()]
        FROM def.dbo.[boxes] b
        Group By b.[PPNumber]  ,b.Bx
        ORDER BY b.Bx
        FOR xml path('')), ' ', ',') as Bxs

FROM def.dbo.[packtable] p
JOIN (SELECT Bx, [PPNumber] FROM def.dbo.[boxes] WHERE (CONCAT(Completed, ' 
  ', CompletedTime) > @sDate AND CONCAT(Completed,' ',  CompletedTime) < 
  @eDate)) b on p.Bx= b.Bx
JOIN def.dbo.[PPNumlist] pp on b.[PPNumber]  = pp.[PPNumber]  

GROUP BY pp.[PPNumber]
ORDER BY pp.[PPNumber]  ;

enter image description here

1 个答案:

答案 0 :(得分:1)

@JNevil提到子查询与主查询无关。我同意这一点,但我不知道最好的方法。但是,我使用函数进行了测试,结果正确。

我所做的只是通过了PN和日期范围而且它有效!

SELECT  
pp.[PPNumber]  as PartNumber,
COUNT(PSN) as ActualCount, 
def.dbo.udf_Get_PackedBoxListByPN(pp.[PPNumber], @sDate,@eDate) as Bxs