Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
sandeepbhutani304
Starting Member
1 Post |
Posted - 2009-03-10 : 05:21:04
|
| I have a table having data:select * from rotaempid workinghrs onDate---------- ----------- -----------------------1 10 2009-01-01 00:00:00.0002 20 2009-01-01 00:00:00.0003 10 2009-01-01 00:00:00.0001 20 2009-01-02 00:00:00.0002 15 2009-01-02 00:00:00.0003 12 2009-01-02 00:00:00.000(6 row(s) affected)I am running following query:select empid, [1],[2] from (select empid, workingHrs, onDate, month(ondate) as d from rota) apivot(sum(workingHrs) for din ([1], [2])) tab_band getting following result:empid 1 2---------- ----------- -----------1 10 NULL2 20 NULL3 10 NULL1 20 NULL2 15 NULL3 12 NULL(6 row(s) affected)Instead I was expecting 10+20=30 for 120+15=35 for 2and 10+12=22 for 3Where I am wrong. I want total hours worked by an emp month-wise Sandeep |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-03-10 : 05:26:03
|
does this work?select empid, [1],[2] from (select empid, workingHrs, onDate, datepart(mm,onDate) as d from rota) apivot(sum(workingHrs) for din ([1], [2])) tab_b |
 |
|
|
Nageswar9
Aged Yak Warrior
600 Posts |
Posted - 2009-03-10 : 05:30:03
|
| try this once,declare @temp table (empid int, workinghrs int, onDate varchar(32))insert into @temp select 1, 10 ,'2009-01-01'insert into @temp select 2, 20, '2009-01-01'insert into @temp select 3, 10, '2009-01-01'insert into @temp select 1, 20, '2009-01-02'insert into @temp select 2, 15, '2009-01-02'insert into @temp select 3, 12,'2009-01-02'select empid, [1],[2] from (select empid,workinghrs,month(ondate) d from @temp) apivot(sum(workingHrs) for din ([1], [2])) tab_b |
 |
|
|
bklr
Master Smack Fu Yak Hacker
1693 Posts |
Posted - 2009-03-10 : 05:30:46
|
| try thisselect sum(case when empid = 1 then workinghrs end) as [1], sum(case when empid = 2 then workinghrs end) as [2],sum(case when empid = 3 then workinghrs end) as [3]from @tab |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-03-10 : 05:33:03
|
quote: Originally posted by bklr try thisselect sum(case when empid = 1 then workinghrs end) as [1], sum(case when empid = 2 then workinghrs end) as [2],sum(case when empid = 3 then workinghrs end) as [3]from @tab
see OP's sample output. the query should beselect empid,sum(case when month(onDate)= 1 then workinghrs end) as [1], sum(case when month(onDate)= 2 then workinghrs end) as [2],sum(case when month(onDate)= 3 then workinghrs end) as [3]from @tabgroup by empid |
 |
|
|
|
|
|
|
|