使用SQL Server我有以下表/数据
CUS_VISIT
Cus_ID Cus_Vis_ID
1 01
1 02
2 01
和
CUS_EVENT
Cus_Event_ID Cus_ID Cus_Vis_ID
001 1 01
002 1 01
和
CUS_XREF
Cus_ID Cus_Event_ID Cus_Prt_ID Cus_Seq_No
1 001 1 1
1 001 2 1
和
CUS_PRT
Cus_ID Cus_Prt_ID Prt_Cd
1 1 1A
1 2 2A
我想获得以下
SQL结果
Cus_ID Prt_Cd Cus_Vis_ID
1 1A,2A 1
我最终得到的是
SQL结果
Cus_ID Prt_Cd Cus_Vis_ID
1 1A 1
1 2A 1
表格由......链接。
CUS_VISIT.Cus_ID = CUS_EVENT.Cus_ID
CUS_VISIT.Cus_Vis_ID = CUS_EVENT.Cus_Vis_ID
CUS_VISIT.Cus_ID = CUS_XREF.Cus_ID
CUS_EVENT.Cus_Event_ID = CUS_XREF.Cus_Event_ID
CUS_XREF.Cus_Prt_ID = CUS_PRT.Cus_Prt_ID
CUS_XREF.Cus_ID = CUS_PRT.Cus_ID
如果我放弃CUS_XREF.Cus_Prt_ID = CUS_PRT.Cus_Prt_ID连接,我几乎可以得到我想要的东西但是我得到了客户的所有部件代码(Prt_Cd),而不仅仅是那次访问的部分代码。
这是我的
select distinct CUS_EVENT.cus_id, CUS_EVENT.cus_visit_id,
(Select CUS_PRT.prt_cd + ',' AS [text()]
From CUS_PRT, CUS_XREF
where
CUS_EVENT.cus_id=XREF.cus_id
and CUS_EVENT.cus_event_id = XREF.cus_event_id
and CUS_XREF.cus_id=CUS_PRT.cus_id
and CUS_XREF.cus_prt_id = CUS_PRT.cus_prt_id
and CUS_XREF.prt_seq_no ='1'
order by CUS_PRT.prt_cd
for XML PATH('')) [Codes]
from CUS_EVENT
我最近做了一个类似的帖子,但没有得到任何具体的帮助。我想我需要另外一个子查询。谢谢你看这个。
答案 0 :(得分:2)
我同意关于它的问题很多。你只需要写for xml
select
V.Cus_ID,
V.Cus_Vis_ID,
stuff(
(
select ', ' + TP.Prt_Cd
from CUS_EVENT as TE
inner join CUS_XREF as TX on TX.Cus_Event_ID = TE.Cus_Event_ID and TX.Cus_ID = TE.Cus_ID
inner join CUS_PRT as TP on TP.Cus_Prt_ID = TX.Cus_Prt_ID and TP.Cus_ID = TE.Cus_ID
where
TE.Cus_Vis_ID = V.Cus_Vis_ID and
TE.Cus_ID = V.Cus_ID
for xml path(''), type
).value('.', 'nvarchar(max)')
, 1, 2, '')
from CUS_VISIT as V
答案 1 :(得分:0)
请尝试这个...但我没有解决这个问题。我已经实现了相同的scenerio。试着让我知道
SELECT
CUS.Cus_ID
, CUS.Cus_Vis_ID
, Prt_Cd=STUFF(
(SELECT
', ' + S.Prt_Cd
FROM CUS_PRT s
INNER JOIN CUS_XREF XREF ON CUS.cus_id=XREF.cus_id AND s.cus_id=XREF.cus_id AND XREF.Cus_Prt_ID = s.Cus_Prt_ID
FOR XML PATH(''), TYPE
).value('.','varchar(max)')
,1,2, ''
)
FROM CUS_EVENT CUS
GROUP BY CUS.Cus_ID,CUS.Cus_Vis_ID