sql - Compare one salary with another and add comments column -
i trying compare 1 salary , add comments column display salary higher who.
i used self join compare not know how include comment column explain higher who.
expect shown below:
empid name salary comments 1 raj 30000 "raj sal less dev , sunil greater prashant,dilip,anil" 2 prashant 24935 "prashant sal less raj,dev,anil,sunil greather dilip" 3 dev 38572 4 anil 29845 5 sunil 48201 6 dilip 12093
use stuff
function within case
statement.
select t1.empid, t1.name, t1.salary, case when t1.salary = (select min(t3.salary) yourtable t3) t1.name + ' has lowest salary.' when t1.salary = (select max(t3.salary) yourtable t3) t1.name + ' has highest salary.' else t1.name +'''s salary less ' + stuff((select ', ' + cast(t2.name varchar(max)) yourtable t2 t1.salary < t2.salary xml path('')),1,1,'') + ' greater ' + stuff((select ', ' + cast(t2.name varchar(max)) yourtable t2 t1.salary > t2.salary xml path('')),1,1,'') + '.' end comments yourtable t1 group t1.empid, t1.name, t1.salary
output
empid name salary comments 1 raj 30000 raj's salary less dev, sunil greater prashant, anil, dilip. 2 prashant 24935 prashant's salary less raj, dev, anil, sunil greater dilip. 3 dev 38572 dev's salary less sunil greater raj, prashant, anil, dilip. 4 anil 29845 anil's salary less raj, dev, sunil greater prashant, dilip. 5 sunil 48201 sunil has highest salary. 6 dilip 12093 dilip has lowest salary.
sql fiddle: http://sqlfiddle.com/#!3/2ebca/63/0
Comments
Post a Comment