I have login credentials along with the status and URL some have multiple userids and some have one only I want to group them by employee id and transpose the data. How can I do it in SQL Server 2019?
Database:
empid name desc uid loc status url
100 Smith AA U1 CA O www
100 Smith AA U2 CA C www
100 Smith BB U3 CA C www
100 Smith CC U4 NY C www
101 Adams BB U5 CA C www
101 Adams CC U6 NY C www
Desired Results
emid name AA loc sta url BB Loc sta url CC loc url
100 Smith U1 CA O www U3 CA C www U4 NY www
100 Smith U2 CA C www
101 Adams U5 CA C www U6 NY www
1条答案
按热度按时间tjrkku2a1#
You could do a dynamic solution:
I created some variables that holds the information you want to group by etc.
@ids
contains list of columns that should identify a unique row@group_field
is the pivoting field that controls how the columns are pivoted@fields
are the pivoted fields table which maps the fields to a label.For dynamic pivots one needs to get a list of groups, which i do by populating the
#t_groups
table. Then, the rest of the code builds the whole thing together and finally executes the dynamic string. You can use print to figure out the final string.Output is:
| empid | name | AA | loc | sta | url | BB | loc | sta | url | CC | loc | sta | url |
| ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ |
| 100 | Smith | U1 | CA | O | www | U3 | CA | C | www | U4 | NY | C | www |
| 100 | Smith | U2 | CA | C | www | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
| 101 | Adams | NULL | NULL | NULL | NULL | U5 | CA | C | www | U6 | NY | C | www |