当重复所有其他字段值时,组合两个不同的字段值

时间:2018-04-16 17:31:42

标签: sql sql-server

我正在尝试在重复选择其他值时组合两个单元格。我试图结合并且永远不会相同的字段是选择中的最后一个。

SELECT field1,field2,field3,field4,field5,field6,table2.name FROM table1 INNER JOIN table2 ON table1.id = table2.table1_id INNER JOIN table2 ON table2.field8 = table2.id WHERE table1.id IN (SELECT table1_id FROM table2_table1 WHERE field8 IN (SELECT field8 FROM table3 WHERE field9 IN (1234))) AND table1.disabled = 0 AND table2.id IN (SELECT field8 FROM table3 WHERE field9 IN (1234))

所以基本上当字段1-6相同并且最后一个字段有多个值时,只显示记录的一行和组合了两个varchar值的最后一个字段。

当前输出是这样的:

商店名称1 1主要街道波特兰OR 97216 ROUTE-AB

商店名称1 1主要街道波特兰OR 97216 ROUTE-BC

我想要这个:

商店名称1 1主要街道波特兰OR 97216 ROUTE-AB,ROUTE-BC

注意:内部联接中的某些逻辑可能已关闭,因为我正在使用实时数据库并且只是尝试用通用数据库替换名称。

1 个答案:

答案 0 :(得分:0)

这是你在找什么?

select field1,field2,field3,field4,field5,field6,max(table2.name)+' '+ case when max(table2.name)=min(table2.name) then '' else min(table2.name) end name

from table1 INNER JOIN table2 ON table1.id = table2.table1_id 
INNER JOIN table2 ON table2.field8 = table2.id 

where table1.id in (select table1_id from table2_table1 where field8 in (select field8 from table3 where field9 in (1234))) and table1.disabled=0 and table2.id in (select field8 from table3 where field9 in (1234))
group by field1,field2,field3,field4,field5,field6