December 17, 2013 at 7:07 am
Hi,
I have a table called employee having data as mentioned below.
emp_nameemp_iddept_noemp_sal
Ranit10011010000
Rahul10022010500
Rajat10033010000
Ravi10041010020
Ridhima10051010900
Raj10063011110
Ranjan10074010230
Ranita10084010220
Rasika10092010010
Rajen10102010030
Now I want to write a query which will show data in below format.
dept_noemp_1empid1emp_2empid2emp_3empid3
10Ranit1001Ravi1004Ridhima1005
20Rahul1002Rasika1009Rajen1010
30Rajat1003Raj1006
40Ranjan1007Ranita1008
Can anyone please let me know how can I achieve it?
December 17, 2013 at 7:29 am
does it help this way ?
declare @employee table
(
emp_name varchar(25),
emp_id int,
dept_no int,
emp_sal int
)
insert @employee (emp_name, emp_id, dept_no, emp_sal)
select 'Ranit', 1001, 10, 10000
union
select 'Rahul', 1002, 20, 10500
union
select 'Rajat', 1003, 30, 10000
union
select 'Ravi', 1004, 10, 10020
union
select 'Ridhima', 1005, 10, 10900
union
select 'Raj', 1006, 30, 11110
union
select 'Ranjan', 1007, 40, 10230
union
select 'Ranita', 1008, 40, 10220
union
select 'Rasika', 1009, 20, 10010
union
select 'Rajen', 1010, 20, 10030
--select [emp_name], [emp_id], [dept_no], [emp_sal] from @employee
SELECT DISTINCT EMP2.dept_no,
SUBSTRING((select ','+ EMP1.emp_name + ' ' + CAST(EMP1.emp_id as nvarchar(max)) + ' ' + CAST(EMP1.emp_sal as nvarchar(max)) as [text()]
from ( select distinct [emp_name], [emp_id], [dept_no], [emp_sal] FROM @employee ) EMP1
where EMP1.dept_no = EMP2.dept_no
ORDER BY EMP1.dept_no
For XML PATH ('')),2, 1000) [List]
FROM ( SELECT DISTINCT [emp_name], [emp_id], [dept_no], [emp_sal] FROM @employee ) EMP2
December 17, 2013 at 7:36 am
Take a look at the articles in my signature about cross tabs. I suspect you will need to use the dynamic version here.
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/
December 18, 2013 at 3:01 am
Thanks. I used pivot to get the required details. Thanks for your help.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply