Skip to content
Advertisement

Assign default values in SQL Server dynamic pivot

Below is pivot query for my requirement.

Below is my script for table creation scripts with data. Table_TraineeInfo is candidate registration details table, Table_Batch_Lookup is batch detail when batch start date and end date base on filling in pivot, Table_Attendance_Log is candidate attendance log.

My current output

enter image description here

I want below output if date is less than or equal to today date fill empty vales to Absent(past date) and Future date should be like that no absent in 12/16/2019 is future date no need to fill absent.

enter image description here

Advertisement

Answer

In a regular (ie non-dynamic) pivot query, you typically use COALESCE() to assign a default value when an aggregate function yields null.

This is a bit more complicated with your dynamic SQL. Basically you need to set a second variable to hold the COALESCE() expressions that you want to put in the SELECT clause. I called it @select_cols; we use COALESCE() and a CASE expression that checks if the date in the future before assigning the default.

Here is your updated code:

Demo on DB Fiddle:

TraineeID | BatchId | Name    | Mobile     | 2019/12/13 | 2019/12/14 | 2019/12/15 | 2019/12/16
--------: | ------: | :------ | :--------- | :--------- | :--------- | :--------- | :---------
      243 |      45 | demo201 | 9888562341 | Present    | Present    | Present    | NULL      
      244 |      45 | demo202 | 9888562342 | Absent     | Absent     | Present    | NULL      
      246 |      45 | demo204 | 9888562344 | Absent     | Present    | Present    | NULL      
      247 |      45 | demo205 | 9999999999 | Absent     | Absent     | Absent     | NULL      
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement