Click here to Skip to main content
15,890,995 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Ent_ID Dest_ID Bank_ID Post_ID
12---- 800---- 1------ 2------
13---- 900---- 1------ 2------

14---- 800---- 1------ 9------
15---- 800---- 1------ 10-----

I'm trying to display this in such a way using SQL so that Ent_ID (12, 13) shows up as one row because their Bank_ID and Post_ID are same.

My ultimate goal is to return this in Datatable for winforms and translate it to datagridview where I have Dest_ID data as checkbox header column.

Bank_ID--Post_ID-- Dest_ID_800--Dest_ID_900
1--------- 2--------- 800------------900
1--------- 9--------- 800------------
1--------- 10------------------------900
Posted

1 solution

Hi,

You can create a static or dynamic pivot query to transform the data.

Here's an example of the static pivot query:
SQL
DECLARE @DataTable TABLE (Ent_ID INT, Dest_ID INT, Bank_ID INT, Post_ID INT);

INSERT INTO @DataTable (Ent_ID, Dest_ID, Bank_ID, Post_ID)
   VALUES (12, 800, 1, 2),
          (13, 900, 1, 2),
          (14, 800, 1, 9),
          (15, 900, 1, 10);

SELECT Bank_ID, Post_ID, [800] AS Dest_ID_800, [900] AS Dest_ID_900
FROM
   (SELECT Dest_ID, Bank_ID, Post_ID
   FROM @DataTable) AS SourceTable
PIVOT (MAX(Dest_ID) FOR Dest_ID IN
   ([800], [900])
) AS PivotTable;

Result:
XML
Bank_ID	Post_ID	Dest_ID_800	Dest_ID_900
1	2	800		900
1	9	800		NULL
1	10	NULL		900

A static query is good if the number of columns (Dest_ID_800, Dest_ID_900, etc.) is fixed. If you want dynamic number of columns (based on the data in Dest_ID column), you can write a dynamic pivot query, i.e. you need to rewrite the static query to be dynamically written.

If you want to write a dynamic pivot query, please take a look here:
1. Dynamic PIVOT in Sql Server[^]
2. An example of a dynamic pivot query[^]
 
Share this answer
 
v2
Comments
Bhis 11-Aug-14 10:51am    
Thank you so much. This is exactly what I was looking for. My column (Dest_ID) is fixed and can only hold 2 IDs. So the static query works great.
Andrius Leonavicius 11-Aug-14 11:17am    
You're welcome. I'm glad to hear that. :)

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