如何在每个唯一标识符的一个字段中插入一列字符串?

时间:2017-02-23 17:48:56

标签: tsql sql-server-2005

如果我的文字没有对齐,我附上了屏幕截图:Undesired Results.

我有一个包含client_id和多行药物的表。我想将每个客户端的所有药物插入到一个逗号分隔的字段中。

我的表格如下:

===================
|Client__ID|DESC   |
|==========|=======|
|500011    |Plavix |
|----------|-------|
|500011    |Zocor  |
|----------|-------|
|500011    |aspirin|
|----------|-------|
|500006    |aspirin|
|----------|-------|
|500006    |Plavix |
|----------|-------|
|500006    |Zocor  |
|----------|-------|
===================

我想要的输出如下:

========================================
|Client__ID|DESC   |MEDS_COMB           |
|==========|=======|====================|
|500011    |aspirin|Plavix,Zocor,aspirin|
|----------|-------|--------------------|
|500006    |aspirin|Plavix,Zocor,aspirin|
|----------|-------|--------------------|
========================================

我的实际结果如下:

========================================
|Client__ID|DESC   |MEDS_COMB           |
|==========|=======|====================|
|500011    |aspirin|NULL                |
|----------|-------|--------------------|
|500006    |aspirin|NULL                |
|----------|-------|--------------------|
========================================

这是我到目前为止所写的查询:

SELECT [CLIENT_ID]
 , [DESC]
 , (STUFF((SELECT CAST(',' + [DESC] AS VARCHAR(MAX)) 
FROM [AZCLMED]
WHERE (CLIENT_ID = [AZCLMED].CLIENT_ID) AND END_DATE IS NULL
         FOR XML PATH ('')), 1, 2, '')) AS MEDS_COMB
FROM [AZCLMED]
ORDER BY [CLIENT_ID] ASC

0 个答案:

没有答案