r1.location
r2.location
に場所を変更すると、あなたが期待する文字列の連結を提供します。
エイリアスを変更して、質問のコードのような数字を使用しないようにしました。
create table t (LastName varchar(32), FirstName varchar(32), Location varchar(32))
insert into t values
('Smith','John','Tampa Hospital')
,('Kennedy','Tom','Maine Hospital')
,('Smith','John','Orlando Hospital')
select distinct lastname, firstname
, Location= stuff((select distinct ',' + i.location
from t as i
where t.lastname = i.lastname
and t.firstname = i.firstname
for xml path('')), 1, 1, '')
from t
リターン:
+----------+-----------+---------------------------------+
| lastname | firstname | Location |
+----------+-----------+---------------------------------+
| Kennedy | Tom | Maine Hospital |
| Smith | John | Orlando Hospital,Tampa Hospital |
+----------+-----------+---------------------------------+
が、問題のコードはlocation
ためサブクエリで外部テーブルを参照しています
select distinct lastname, firstname
, Location= stuff((select distinct ',' + t.location
from t as i
where t.lastname = i.lastname
and t.firstname = i.firstname
for xml path('')), 1, 1, '')
from t
リターン:
+----------+-----------+------------------+
| lastname | firstname | Location |
+----------+-----------+------------------+
| Kennedy | Tom | Maine Hospital |
| Smith | John | Orlando Hospital |
| Smith | John | Tampa Hospital |
+----------+-----------+------------------+
私はそれを読んでスレッドが目的を説明していない私のスクリプトのコードの。あなたが参照しているスレッドは、出力を "aaa、bbb、ccc"と表示します。これは私のスクリプトでは起こっていません。 STUFF機能がここで使われている理由はわかりません。 – jackstraw22
これは誤ってコーディングされているためです。サブクエリでDISTINCTを使用すると、コンマ区切りのリストが生成されません。 –
@SeanLange私は、 'r2.location'ではなく' r1.location'が 'distinct'を使用しているのではないと言います。 http://rextester.com/TRNL18297 - あなたは正しいです、それは間違ってコード化されています。 – SqlZim