简体   繁体   中英

Rolling up multiple rows into a single row and column for SQL Server data

I want is put the multilpe rows in a single row and column and I'm using MICROSOFT SQL Server. I tried the stuff command but I getting the error The multi-part identifier "" could not be bound. Please Help! Thanks

select a.CLAIMNO, e.INVNO, d.MSISDN, a.BATCHNO, b.CUSTOMER, b. PRODNO, 
b.INCENTIVE, b.QTY, b.STATUS, 
b.ROWNUM, b.RECEIVEDBY, b.RECEIVEDDATE, b.REMARKS, b.PESOVALUE
from CSPC_CLAIMHDR a
left join CSPC_CLAIMDTL b on a.PRFNO = b.PRFNO and a.CLAIMNO = b.CLAIMNO 
left join CSPC_CUSTOMERS c on c.CUSTNAME = b.CUSTOMER 
left join CSPC_PMACCOUNT d on d.CUSTCODE = c.CUSTCODE 
left join CSPC_INVOICEHDR e on e.CLAIMNO = a.CLAIMNO
where upper(a.PRFNO) = 'MOM--0108' and b.INCENTIVE not like '%POINTS%' and 
a.APPROVEDBY is not null order by b.CUSTOMER

this produces [Result][1]

CLAIMNO   INVNO 
618       SO202
618       SO213
618       SO932
618       SO133
618       SO873
658       SO123
658       SO877

and I want it to produce it like this below.

CLAIMNO   INVNO
618       SO202,SO213,SO932,SO133,SO873
658       SO123,SO877

Your statement begins with

SELECT a.CLAIMNO, STUFF((...inner select query that aliases table a...))

It is the inner select query that aliases table a, not the outer one. A.claimno is not a thing/doesn't exist by the time processing the sql gets to that outer level

Here is a simpler example:

select a.thing, (select a.otherthing from table a)

a.thing does not exist outside the brackets. These are valid

It isn't really clear what you're trying to do so I can't advise on what you should do to achieve the result you want, I can only answer why you're getting this error

You'd be better off removing the outer query, and the stuff call and just posting up your inner query as a new question with “this produces (paste results) and I want it to produce (create desired results), please help”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM