Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a PivotTable in Transact/SQL?

My source data table is

MemID Condition_ID Condtion_Result
----------------------------------
1     C1           0
1     C2           0
1     C3           0
1     C4           1
2     C1           0
2     C2           0
2     C3           0
2     C4           0

The expected view I want to create is ....

MemID C1 C2 C3 C4
------------------
1     1  0  0  1
2     0  0  0  1

Here is the other condition. In the above source table example , only 4 rows for a given MemID. This number will vary in the actual situation. My pivot table(or any other solution) should pick it any number of condition results and display them as columns. How to do it ?

like image 576
LaysomeSmith Avatar asked Jul 23 '12 17:07

LaysomeSmith


People also ask

Is there a PIVOT function in SQL?

SQL PIVOT diagramYou can use PIVOT to rotate rows in a table by turning row values into multiple columns. The following diagram illustrates what PIVOT can do where we take 4 rows of data and turn this into 1 row with 4 columns. As you can see, the PIVOT process converts rows into columns by pivoting the table.

How do I PIVOT two columns in SQL Server?

You gotta change the name of columns for next Pivot Statement. You can use aggregate of pv3 to sum and group by the column you need. The key point here is that you create new category values by appending 1 or 2 to the end. Without doing this, the pivot query won't work properly.

What is PIVOT in SQL w3schools?

It lets you add and remove values, perform calculations, and to filter and sort data sets. PivotTable helps you structure and organize data to understand large data sets. The data that you use needs to be in tabular format. The tabular form is data in a table format (rows and columns).

How do I link a PivotTable to SQL Server?

Connect to a new external data source To create a new external data connection to SQL Server and import data into Excel as a table or PivotTable, do the following: Click Data > From Other Sources. Click the connection you want. Click From SQL Server to create a connection to a SQL Server table.


1 Answers

You need to use a PIVOT. You can use either a STATIC PIVOT where you know the values of the columns to transform or a DYNAMIC PIVOT where the columns are unknown until execution time.

Static Pivot (See SQL Fiddle with Demo):

select *
from 
(
    select memid, Condition_id, Condition_Result
    from t
) x
pivot
(
    sum(condition_result)
    for condition_id in ([C1], [C2], [C3], [C4])
) p

Dynamic Pivot (See SQL Fiddle with Demo):

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.condition_id) 
            FROM t c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


set @query = 'SELECT memid, ' + @cols + ' from 
            (
                select MemId, Condition_id, condition_result
                from t
           ) x
            pivot 
            (
                sum(condition_result)
                for condition_id in (' + @cols + ')
            ) p '


execute(@query)

Both will generate the same results.

like image 139
Taryn Avatar answered Oct 20 '22 19:10

Taryn