Saturday, December 7, 2024

Dynamic Pivot with SQL in SQL Server

 In our example we have a Dynamic Survey form in the database which we would use to take survey of employees across an agency. Now when we have collected the survey we need to generate a report in pivot format which would give u one row per employee and in the columns we would get answers to each question. Interesting!

Lets look at the options available in SQL Server.

To pivot your query and transform it into a format where each row represents an employee and the columns contain answers for each question, you can use a PIVOT operation.

Steps:

  1. Aggregate the Data:

    • Use the base query to gather the employee data, question texts, and their corresponding answers.
  2. Prepare the Pivot:

    • Use the PIVOT operator to dynamically transform rows (questions and answers) into columns for each question.
If the questions are dynamic and you don't know them in advance, you need to dynamically generate the column list using dynamic SQL.

Handling Dynamic Questions:

If the list of questions is not fixed and changes frequently, you can use dynamic SQL to generate the column list automatically.


DECLARE @Columns NVARCHAR(MAX);
DECLARE @SQL NVARCHAR(MAX);

-- Step 1: Generate the Column List Using FOR XML PATH
SELECT @Columns = STUFF((
    SELECT DISTINCT ',' + QUOTENAME(QUESTION)
    FROM QUIZ_QUESTIONS
    WHERE QUESTIONID IN (
        SELECT DISTINCT QUESTIONID
        FROM QUIZ_ATTEMPT_RESULT
        WHERE QUIZASSIGNID IN (SELECT QUIZASSIGNID FROM QUIZ_ASSIGNMENT WHERE QUIZID = 1)
    )
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '');

-- Step 2: Construct the Dynamic Pivot Query
SET @SQL = '
WITH BaseData AS (
    SELECT 
        EMPLOYEES.EMPLOYEEID,
        EMPLOYEES.FIRSTNAME + '' '' + EMPLOYEES.LASTNAME AS EmployeeName,
        QUIZ_QUESTIONS.QUESTION AS QuestionText,
        QUIZ_QUESTION_ANSWERS.ANSWER AS Answer
    FROM [dbo].[QUIZ_ASSIGNMENT]
    INNER JOIN EMPLOYEES
        ON EMPLOYEES.EMPLOYEEID = [QUIZ_ASSIGNMENT].EMPLOYEEID
    INNER JOIN [dbo].[QUIZ_ATTEMPT_RESULT]
        ON QUIZ_ATTEMPT_RESULT.QUIZASSIGNID = QUIZ_ASSIGNMENT.QUIZASSIGNID
    INNER JOIN [dbo].[QUIZ_QUESTION_ANSWERS]
        ON QUIZ_QUESTION_ANSWERS.ANSWERID = QUIZ_ATTEMPT_RESULT.ANSWERID
    INNER JOIN [dbo].[QUIZ_QUESTIONS]
        ON QUIZ_QUESTIONS.QUESTIONID = QUIZ_ATTEMPT_RESULT.QUESTIONID
    WHERE QUIZ_ASSIGNMENT.QUIZID = 1
)
SELECT *
FROM (
    SELECT 
        EmployeeName,
        QuestionText,
        Answer
    FROM BaseData
) AS SourceTable
PIVOT (
    MAX(Answer)
    FOR QuestionText IN (' + @Columns + ')
) AS PivotTable;
';

-- Step 3: Execute the Dynamic SQL
EXEC sp_executesql @SQL;


Sample Input Data:

NameQuestionAnswer
John SmithWhat is your name?John
John SmithWhat is your age?30
Jane DoeWhat is your name?Jane
Jane DoeWhat is your age?25


Sample Output Data:

NameWhat is your name?What is your age?
John SmithJohn30
Jane DoeJane25

Sunday, September 23, 2012

HTML5, Draw Rounded Rectangle on Canvas

Example below will draw rounded rectangle:

function doRoundedRectangle(c,sx,sy,ex,ey,r) {
 var ctx = c.getContext("2d");
 var r2d = Math.PI/180;
 if( ( ex - sx ) - ( 2 * r ) < 0 ) { r = ( ( ex - sx ) / 2 ); } //ensure that the radius isn't too large for x
 if( ( ey - sy ) - ( 2 * r ) < 0 ) { r = ( ( ey - sy ) / 2 ); } //ensure that the radius isn't too large for y
 ctx.beginPath();
 ctx.moveTo(sx+r,sy);
 ctx.lineTo(ex-r,sy);
 ctx.arc(ex-r,sy+r,r,r2d*270,r2d*360,false);
 ctx.lineTo(ex,ey-r);
 ctx.arc(ex-r,ey-r,r,r2d*0,r2d*90,false);
 ctx.lineTo(sx+r,ey);
 ctx.arc(sx+r,ey-r,r,r2d*90,r2d*180,false);
 ctx.lineTo(sx,sy+r);
 ctx.arc(sx+r,sy+r,r,r2d*180,r2d*270,false);
 ctx.closePath();
};

Parameters:
c = Canvas object
sx = Start x position
sy = Start y position
ex = End x position
ey = End y position
r = radius for rounded corners

Tuesday, March 13, 2012

HttpException: The URL-encoded form data is not valid

An httpexception might be poping up in most of the ASP.NET 2.0 applications where there are lot of user controls on your view. Microsoft security update MS11-100 limits the maximum number of form keys, files, and JSON members to 1000 in an HTTP request. Because of this change, ASP.NET applications reject requests that have more than 1000 of these elements.
HTTP clients that make these kinds of requests will be denied, and an error message will appear in the web browser. The error message will usually have an HTTP 500 status code.


Exception information in Windows event log will contain:
Exception type: HttpException
Exception message: The URL-encoded form data is not valid

ASP.NET 2.0
If your application view reaches over 1000 elements, than you will need to configure this value in your web.config file. And following lines need to be added:

<configuration>
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="1000" />
</appSettings>
</configuration>


You should set the value to your need, and it should be any value over 1000. You can give value under 1000 as well if your application works on it.

ASP.NET 1.1
For .NET 1.1 web applications you will have to set a DWORD in registry. Following is the key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\1.1.4322.0\MaxHttpCollectionKeys

JSON Limit
Applications that hit this limit for JSON payloads can configure as follows:

<configuration>
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
</appSettings>
</configuration>


Reference:
http://support.microsoft.com/kb/2661403

Wednesday, January 11, 2012

Commodo Antivirus, Manually update virus definition

Download the latest full AV database:

For respective CIS version, we have different complete bases.cav:

1. For CIS 4.x
Following link points to latest complete bases.cav always
http://download.Comodo.com/av/updates40/sigs/bases/bases.cav

2. For CIS 5.0
Following link points to latest complete bases.cav always
http://download.Comodo.com/av/updates50/sigs/bases/bases.cav

3. For CIS 5.3 & 5.4
i) Download
http://download.Comodo.com/av/updates51/sigs/bases/bases.cav.z
ii)
Use 7-zip from http://www.7-zip.org/download.html , or your archiver program of choice that can handle 7z archives and unpack it. After unpacking you will have to rename the file to bases.cav.

4. For CIS 5.5
i) Download
http://download.Comodo.com/av/updates55/sigs/bases/bases.cav.z
ii)
Use 7-zip from http://www.7-zip.org/download.html , or your archiver program of choice that can handle 7z archives and unpack it. After unpacking you will have to rename the file to bases.cav.

5. For CIS 5.8
i) Download
http://download.Comodo.com/av/updates58/sigs/bases/bases.cav.z
ii)
Use 7-zip from http://www.7-zip.org/download.html , or your archiver program of choice that can handle 7z archives and unpack it. After unpacking you will have to rename the file to bases.cav.

Activating the download:

1. Save the downloaded file on your computer

2. Reboot in Safe-Mode

3. Open explorer and go to C:\Program files\Comodo\Comodo internet security\scanners and copy the downloaded bases.cav here

4. Reboot your system in normal mode