Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have table with staffid and evaluation date i wants to pivot that date as date1,date2 and date 3.

What I have tried:

select * from 
(  select staffid, effectivedate  from EvaluationDetail) src
pivot
(  avg(staffid)  for effectivedate in ([effectivedate1], [effectivedate2], [effectivedate3]) ) piv;
Posted
Updated 9-Dec-18 8:18am
Comments
OriginalGriff 5-Dec-18 8:07am    
And?
What did that do that you didn't expect, or not do that you did?
What have you tried?
Where are you stuck?
What help do you need?
neeraj_ 6-Dec-18 4:39am    
Sir, I want the out put like this-
Staff id effectivedate1 effectivedate2 effectivedate3
9240 2017-04-01 2018-04-01 2018-09-01
Santosh kumar Pithani 5-Dec-18 9:04am    
Don't pass "[effectivedate1], [effectivedate2], [effectivedate3]" like this instead of that
values should be date like "[2018-04-12],[2018-05-28]"..
neeraj_ 6-Dec-18 5:05am    
Sir, I want the out put like this-
Staffid effectivedate1 effectivedate2 effectivedate3
9240 2017-04-01 2018-04-01 2018-09-01

Guessing slightly on how you want to populate the columns, try something like this:
SQL
WITH cteOrderedDates As
(
    SELECT
        StaffId,
        EffectiveDate,
        ROW_NUMBER() OVER (PARTITION BY StaffId ORDER BY EffectiveDate DESC) As RN
    FROM
        EvaluationDetail As D
)
SELECT
    StaffId,
    MAX(CASE RN WHEN 3 THEN EffectiveDate END) As EffectiveDate1,
    MAX(CASE RN WHEN 2 THEN EffectiveDate END) As EffectiveDate2,
    MAX(CASE RN WHEN 1 THEN EffectiveDate END) As EffectiveDate3
FROM
    cteOrderedDates
WHERE
    RN <= 3
GROUP BY
    StaffId
;
 
Share this answer
 
Comments
neeraj_ 26-Dec-18 2:17am    
thank you so much sir.

worked properly
You have to enumerate the dates you want to include e.g.
SQL
select * from 
(  select staffid, effectivedate  from #EvaluationDetail) src
pivot
(  count(staffid)  for effectivedate in ([2018-01-10], [2018-03-10], [2018-02-05]) ) piv;
Note I've changed the function to count because the average of a staffid means nothing at all.

I've assumed that the column effectivedate is declared as type date - specifically not datetime!

If you want that list of dates to be determined by the data itself then you will need some dynamic SQL.
 
Share this answer
 
Comments
neeraj_ 6-Dec-18 4:38am    
Sir,
Actually i don't want the count of the date .
i want the output like
Staff id effectivedate1 effectivedate2 effectivedate3
9240 2017-04-01 2018-04-01 2018-09-01

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900