| Author |
Topic |
|
ramprasad_554
Starting Member
1 Post |
Posted - 2007-02-14 : 06:30:58
|
| Pivot:--->>> Assume that you have table A that contains data regarding tips earned for each employee in the following format: A(empid, Mon_tips, Tues_tips, Wed_tips, Thu_tips, Fri_tips) .Write a SQL Query that will convert the data from table A into table B with the following format: B(empid, day, tips) where the column day can take the values (Mon, Tue, Wed, Thu, Fri).Create table A (empid int, mon_tips int, tue_tips int, wed_tips int, thu_tips int, Fri_tips int);Insert into A value (1, 10, 20, 30, 20,10);Insert into A value (2, 10, 20, 30, 40,50);>>> Unpivot: Reverse of Question 2 above. Assume that you have a table B write a SQL to convert the data into table A.>>>>Print the employee id and the difference in salary from the employee with the next lower salary.Print -1 if the employee has the lowest salary in the organization.Create table emp(eid int sal int);Insert into emp Values(1,100000);Insert into emp Values(2,80000); |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-02-14 : 09:28:51
|
| [code]-- prepare sample datadeclare @A table (empid int, mon_tips int, tue_tips int, wed_tips int, thu_tips int, Fri_tips int)Insert into @A values (1, 10, 20, 30, 20,10)Insert into @A values (2, 10, 20, 30, 40,50)-- show the expected resultselect empid, 'mon', mon_tips from @a union allselect empid, 'tue', tue_tips from @a union allselect empid, 'wed', wed_tips from @a union allselect empid, 'thu', thu_tips from @a union allselect empid, 'fri', fri_tips from @a[/code]Peter LarssonHelsingborg, Sweden |
 |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-02-14 : 09:41:59
|
Use the new PIVOT function. Or the UNPIVOT function,Or...-- prepare sample datadeclare @t table (empid int, weekdayname varchar(3), value int)insert @tselect 1, 'mon', 10 union allselect 2, 'mon', 10 union allselect 1, 'tue', 20 union allselect 2, 'tue', 20 union allselect 1, 'wed', 30 union allselect 2, 'wed', 30 union allselect 1, 'thu', 20 union allselect 2, 'thu', 40 union allselect 1, 'fri', 10 union allselect 2, 'fri', 50-- show the expected resultselect empid, max(case when weekdayname = 'mon' then value end) as mon_tips, max(case when weekdayname = 'tue' then value end) as mon_tips, max(case when weekdayname = 'wed' then value end) as mon_tips, max(case when weekdayname = 'thu' then value end) as mon_tips, max(case when weekdayname = 'fri' then value end) as mon_tipsfrom @tgroup by empidorder by empid Peter LarssonHelsingborg, Sweden |
 |
|
|
|
|
|