[英]Stuff() Not Grouping Accurately
I am using an older version of SQL Server and trying to convert rows to concatenated columns.我正在使用旧版本的 SQL Server 并尝试将行转换为连接的列。 From researching here on stack overflow I see that I should be using STUFF().
通过对堆栈溢出的研究,我发现我应该使用 STUFF()。 However, when I attempt to replicate the answers I found here, I can't get the grouping correct.
但是,当我尝试复制我在此处找到的答案时,无法正确分组。 Instead of concatenating names tied to my GROUP BY, it's concatenating every single row and then just duplicating the results for every single row.
它不是连接与我的 GROUP BY 相关联的名称,而是连接每一行,然后只复制每一行的结果。
My base table #Temp is laid out as such:我的基表 #Temp 布局如下:
CleanName![]() |
FullName![]() |
Total![]() |
---|---|---|
Doe, Jane![]() |
DO, JANE![]() |
4 ![]() |
Doe, Jane![]() |
DOE, JANE S.![]() |
15 ![]() |
Doe, Jane![]() |
Doe, J.![]() |
23 ![]() |
Smith, John![]() |
Smith, J.![]() |
4 ![]() |
Smith, John![]() |
Smith, Jon![]() |
10 ![]() |
Smith, John![]() |
Smith, John![]() |
103 ![]() |
I am trying to get results like this:我试图得到这样的结果:
CleanName![]() |
Concat_FullName ![]() |
Sum(Total)![]() |
---|---|---|
Doe, Jane![]() |
DO, JANE;![]() ![]() ![]() |
42 ![]() |
Smith, John![]() |
Smith, J.;![]() ![]() ![]() |
117 ![]() |
This is what I tried running based on my research on stack overflow:这是我根据对堆栈溢出的研究尝试运行的:
SELECT
STAND_PRESC_NAME,
CONCAT_FULLNAME = STUFF(( SELECT '; ' + FULLNAME
FROM #TEMP
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,''),
SUM(TOTAL)
FROM #TEMP
GROUP BY STAND_PRESC_NAME
However what resulted was every row concatenated together which is not the desired results:然而,结果是每一行都连接在一起,这不是预期的结果:
CleanName![]() |
Concat_FullName ![]() |
Sum(Total)![]() |
---|---|---|
Doe, Jane![]() |
DO, JANE;![]() ![]() ![]() ![]() ![]() ![]() |
42 ![]() |
Smith, John![]() |
DO, JANE;![]() ![]() ![]() ![]() ![]() ![]() |
117 ![]() |
How do I need to alter my STUFF() usage to appropriately group by CleanName?我需要如何更改我的 STUFF() 用法以按 CleanName 适当分组?
You forgot to add the correlation:您忘记添加相关性:
SELECT
STAND_PRESC_NAME,
CONCAT_FULLNAME = STUFF(( SELECT '; ' + FULLNAME
FROM #TEMP t
WHERE t.STAND_PRESC_NAME = t2.STAND_PRESC_NAME -- this
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,''),
SUM(TOTAL)
FROM #TEMP t2
GROUP BY STAND_PRESC_NAME
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.