我有两张桌子:CONFIRMATION& CONFIRMATION_PRESS
CONFORMATION 表如下所示:
ID_CONF | ID_LOT | QTY
1005 175 25
1006 175 24
1007 175 23
1008 176 50
CONFIRMATION_PRESS 表如下所示:
ID_CONF | ID_PRESS
1005 11
1005 22
1005 33
1006 12
1006 13
1007 14
现在我想从CONFIRMATION表中获取ID_LOT = 175的所有数据,但我需要以逗号分隔值的ID_PRESS。
例如,对于ID_LOT 175,应显示以下结果:
ID CONF | ID_LOT | QTY | ID_PRESS
--------+--------+-----+----------
1005 175 25 11,22,33
1006 175 24 12,13
1007 175 23 14
我的查询如下:
SELECT
C.ID_CONF,
C.QTY,
C.ID_LOT,
STUFF((
SELECT CAST(',' AS VARCHAR(MAX)) + CAST(CP.ID_PRESS AS VARCHAR(5))
FROM CONFIRMATION C,
CONFIRMATION_PRESS CP
WHERE
C.ID_CONF = CP.ID_CONF
FOR XML PATH('')), 1, 1, '') PRESS_CSV
FROM
CONFIRMATION C
WHERE
C.ID_LOT = 175
但它返回此输出:
ID CONF | ID_LOT | QTY | ID_PRESS
--------+--------+-----+------------------
1005 175 25 11,22,33,12,13
1006 175 24 11,22,33,12,13
1007 175 23 11,22,33,12,13
我在这里做错了什么?
请帮忙!
问候!
答案 0 :(得分:1)
不要再次加入子查询上的CONFIRMATION表。您需要与主查询相关的行。
SELECT
C.ID_CONF,
C.QTY,
C.ID_LOT,
STUFF((
SELECT CAST(',' AS VARCHAR(MAX)) + CAST(CP.ID_PRESS AS VARCHAR(5))
FROM CONFIRMATION_PRESS CP
WHERE CP.ID_CONF = C.ID_CONF
FOR XML PATH('')), 1, 1, '') PRESS_CSV
FROM CONFIRMATION C
WHERE C.ID_LOT = 175
答案 1 :(得分:1)
Begin Tran
Create Table CONFIRMATION (ID_CONF Int,ID_LOT Int,QTY numeric)
INSert into CONFIRMATION
Select 1005,175,25 Union All
Select 1006,175,24 Union All
Select 1007,175,23 Union All
Select 1008,176,50
Create Table CONFIRMATION_PRESS (ID_CONF int ,ID_PRESS INt )
Insert into CONFIRMATION_PRESS
Select 1005,11 Union All
Select 1005,22 Union All
Select 1005,33 Union All
Select 1006,12 Union All
Select 1006,13 Union All
Select 1007,14
--Select *from CONFIRMATION Inner Join
--CONFIRMATION_PRESS On CONFIRMATION_PRESS.ID_CONF=CONFIRMATION.ID_CONF
--Where CONFIRMATION.ID_LOT=175
SELECT
C.ID_CONF,
C.QTY,
C.ID_LOT,
STUFF((
SELECT ', ' + CONVERT(Nvarchar,CP.ID_PRESS)
from
CONFIRMATION_PRESS CP
WHERE
C.ID_CONF = CP.ID_CONF
FOR XML PATH('')), 1, 2, '') PRESS_CSV
FROM
CONFIRMATION C
WHERE
C.ID_LOT = 175
RollBack Tran