-7

Please help me to get this output.

My Input:

-----------------------------------------------------
EMP_Id |    EMP_Name |  Date_Worked             |   Enc_No
---------------------------------------------------
100    |    Aj       |  2016-10-10 00:00:00.000 |   123
100    |    Aj       |  2016-10-10 00:00:00.000 |   124
101    |    Siv      |  2016-10-10 00:00:00.000 |   125
101    |    Siv      |  2016-10-11 00:00:00.000 |   126
102    |    Nav      |  2016-10-10 00:00:00.000 |   127
102    |    Nav      |  2016-10-11 00:00:00.000 |   128    
--------------------------------------------------------

I need output like this

---------------------------------------------------------
EmplyeeId | EmplyeeName | 10/10/2016 | 11/10/2016
---------------------------------------------------------
100       | Aj          | 2          |  0
101       | Siv         | 1          |  1
102       | Nav         | 1          |  1
---------------------------------------------------------
halfer
  • 19,824
  • 17
  • 99
  • 186
Raja A
  • 53
  • 1
  • 7

2 Answers2

1
 SELECT * FROM #A
 PIVOT
(
 count(Enc_No) 
  FOR DATE_WORKED IN([2016-10-10],[2016-10-11])
) PIV;

enter image description here

Chanukya
  • 5,833
  • 1
  • 22
  • 36
0

I think you are talking about dynamic pivot . I implemented dynamic pivot in my project .I give you sample script as per your input .Please check it . I am sure it will be helpful for you .

Here EmployeeWork is a TableName .

DECLARE @FactorText varchar(max)=null

SELECT @FactorText = COALESCE(@FactorText + '], ', '') + CAST('[' + FactorText AS VARCHAR(50)) 
                     FROM (SELECT DISTINCT CONVERT(varchar, Date_Worked, 103) as FactorText FROM EmployeeWork) AS EmployeeWork

                    SET  @FactorText =  @FactorText + ']'

DECLARE @DynamicPIVOT AS VARCHAR(MAX)

                SELECT @DynamicPIVOT = 'SELECT EMP_Id,emp,' + @FactorText + ' FROM ( select EMP_Id , EMP_Name as emp, EMP_Name
                as AppliedValue,  CONVERT(varchar, Date_Worked, 103) as FactorText FROM EmployeeWork
                ) EmployeeWorkData

                PIVOT
                      (
                   count(AppliedValue) FOR FactorText IN (' + @FactorText + ')
                      ) Result;'


EXEC (@DynamicPIVOT)

If any query then tells me.As per your requirement, it's working perfectly.

Thanks .

Ronak Patel
  • 630
  • 4
  • 15