简体   繁体   中英

SQL Server 2016 - Transpose column of integers to row by day

I need to transpose one of the columns in the data date to a row of string and group by 2 other columns. My sample data consists of the following data:

在此处输入图像描述

I need the result to look like this:

在此处输入图像描述

That is all the LNs in one row per Employee code, per day.

I tried the below code -

DECLARE @Process_Conditions_Loans VARCHAR(500)

SELECT
    t1.EmplCode,
    t1.LogDate,
    @Process_Conditions_Loans = CONCAT(COALESCE(@Process_Conditions_Loans + ',', ''),PS2)
FROM
    #temp t1
WHERE
    LN IS NOT NULL 
GROUP BY
    EmplCode, LogDate

But I am getting an error

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.

I can not use group_concat since I am using SQL Server 2016.

Any help would be great appreciated.

Thanks, JH

You can use the older form of string aggregation:

select emplcode, logdate,
       stuff( (select concat(', ', ln)
               from t
               where t.emplcode = el.emplcode and t.logdate = el.logdate
               order by ln
               for xml path ('')
              ), 1, 2, ''
            )
from (select distinct emplcode, logdate
      from t
     ) el

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