Jeff Smith Blog

Random Thoughts & Cartesian Products with Microsoft SQL Server

Pivot Sample (C#)

private void Sample()

        {
            // call this from a form ....

            SqlConnection conn;

            SqlCommand com;

 

            DataGrid dg = new DataGrid();

            dg.Parent = this;

            dg.Dock = DockStyle.Fill;

 

            String SQL =

                "select o.customerID, c.CompanyName, p.productName, sum(od.quantity) as Qty " +

                " from orders o " +

                " inner join [order details] od on o.orderID = od.orderID " +

                " inner join Products p on od.ProductID = p.ProductID " +

                " inner join Customers c  on o.CustomerID = c.CustomerID " +

                " group by o.customerID, c.CompanyName, p.ProductName " +

                " order by o.customerID";

 

            conn = new SqlConnection( "Server=(local);Database=Northwind;uid=xx;pwd=xx");

            conn.Open();

            com = new SqlCommand(SQL, conn);

            try

            {

                dg.DataSource = Pivot(com.ExecuteReader(),"CustomerID","ProductName","Qty");

            }

            catch (SqlException ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

 

Legacy Comments


Drew
2005-05-25
re: Pivot Sample (C#)
This does not work, do you need to have a library included?

Drew Again
2005-05-25
re: Pivot Sample (C#)
My Bad, didn't see function link.

leon
2005-08-02
HINT: The word "Pivot" in the sample above is a link to the code!!
brilliant example!
i had the same experience as Drew at first --> i couldn't find the link to the "Pivot" function

koorosh zahedi
2005-10-09
re: Pivot Sample (C#)
hello
please send me this sample with VB language
bye

thankfullprogrammer
2006-07-21
re: Pivot Sample (C#)
"hello
please send me this sample with VB language
bye
"

Ugh... can you do ANY work for yourself?

srous
2006-09-05
re: Pivot Sample (C#)

This is great - worked first time.

I'm especuially impressed that extra PK columns are also included in the results set by default

eric turner
2008-07-08
re: Pivot Sample (C#)
random pivot rules

oalp
2009-11-06
re: Pivot Sample (C#)
Great job. thanks for sharing.