2

I'm not sure if this is possible from with a SQL query, but I'll give it a go.

I'm developing a SharePoint web part in C# that connects to a SQL database and runs a query, then databinds that result set to a gridview. It's working fine, but I have a small snag. For the most part, my query will return exactly one result for every field. I am displaying the information vertically, so it looks roughly like this:

Customer Name           Mr. Customer
Customer Address        980 Whatever St.
Customer City           Tallahassee

Everything displays fine. However, one of the tables in the database will pretty much always return multiple results. It lists different types of materials used for different products, so the schema is different because while each customer will obviously have one name, one address, one city, etc., they will all have at least one product, and that product will have at least one material. If I were to display that information on its own, it would look something like this:

Product              Steel Type              Wood Type             Paper Type
-----------------------------------------------------------------------------
Widget               Thick                   Oak                   Bond
Whatsit              Thin                    Birch
Thingamabob                                  Oak                   Cardstock

Ideally, I suppose the end result would be something like:

Customer Name           Mr. Customer
Customer Address        980 Whatever St.
Customer City           Tallahassee
Widget Steel            Thick
Widget Wood             Oak
Widget Paper            Bond
Whatsit Steel           Thin
Whatsit Wood            Birch
Thingamabob Wood        Oak
Thingamabob Paper       Cardstock

Another acceptable result could be something like the following, adding a few columns but only returning multiple results for those fields:

Customer Name        Mr. Customer
Customer Address     980 Whatever St.
Customer City        Tallahassee
Product              Steel Type              Wood Type             Paper Type
Widget               Thick                   Oak                   Bond
Whatsit              Thin                    Birch
Thingamabob                                  Oak                             

I'm open to any suggestions. I'd like to include this in the result set without a separate query, if that's possible. Here is the code that I am using to pull in the data:

                    SqlDataAdapter da = new SqlDataAdapter();
                    da.SelectCommand = cmd;
                    DataSet ds = new DataSet();
                    da.Fill(ds, "Specs");
                    DataSet flipped_ds = FlipDataSet(ds);
                    DataView dv = flipped_ds.Tables[0].DefaultView;
                    GridView outputGrid = new GridView();
                    outputGrid.ShowHeader = false;
                    outputGrid.DataSource = dv;
                    outputGrid.DataBind();
                    Controls.Add(outputGrid);

I would list my SQL query, but it's enormous. I'm pulling in well over one hundred fields right now, with lots of SUBSTRING formatting and concatenation, so it would be a waste of space, but it's really a fairly simple query where I'm selecting fields with the AS statement to get the names that I want, and using a few LEFT JOINs to pull in the data I need without several queries. The schema of the product/material table is something like this:

fldMachineID
fldProductType
fldSteel
fldWood
fldPaper

So obviously, each customer has a number of entries, one for each different fldProductType value. If I'm leaving anything out, I can add it. Thanks for everyone's time and help!

Geo Ego
  • 1,315
  • 7
  • 27
  • 53
  • What database are you using, and how do you expect those values to be returned? – Peter Lang Feb 26 '10 at 15:57
  • I'm not sure I understand. As it stands, it looks to me that all you need to do is add a LEFT JOIN. But from your question, it's obvious you know about LEFT JOINS so it can't be that 'simple'. That brings me back to 'I'm not sure I understand'. Perhaps adding the expected output would clear things up. – Lieven Keersmaekers Feb 26 '10 at 16:02
  • I'm using SQL Server 2005. I edited the original question to better reflect my desired results. Now that I've done that, I'm sure you can see that adding another LEFT JOIN will now give me multiple sets of results (one for each result in fldProductType) but in the context of the datagrid, I really need just one column of data type names and a second column of results. – Geo Ego Feb 26 '10 at 16:04
  • Is there a reason you are staying away from multiple queries? I see 3 options: 1) Run multiple queries and join the resulting data tables together using a data relationship, 2) Run a single query using a left join and deal with the "extra" data in your client application, 3) Concatenate the additional field results into a single field on your result. – Chris Porter Feb 26 '10 at 16:14
  • The only reason I'm staying away from multiple queries is to simplify the C# as much as possible. Right now, I'm able to very easily databind the datagrid and get the results that I need; however, if the best option is multiple queries, I'm willing to do it, but not exactly sure how. If there was a way to simply trim out all of the additional results after the query is run, I'd be open to doing that, too, even if I have to build the datagrid row-by-row (I'm tempted to do that anyway to give me better control over the CSS class definitions). Would you mind giving some examples? Thanks. – Geo Ego Feb 26 '10 at 16:18
  • edit your question with the two tables you are trying to query on. Include the table names, columns and their data types of all the columns to include in the query. add a comment onto my answer, so I know to look back. and I'll see if if can write the query for you. – KM. Mar 01 '10 at 20:04
  • Have you considered using the SQL PIVOT operator? – Ahmad Mar 02 '10 at 11:32
  • I played around with KM's solution and checked the link provided by zespri. This is, I think, exactly what I asked for. I ended up going a slightly different direction after reevaluating what I really needed, but this is certainly the answer for this question as asked. Thanks for your help! – Geo Ego Mar 05 '10 at 16:33

2 Answers2

2

try this:

DECLARE @TableA  table (RowID int, Value1 varchar(5), Value2 varchar(5))
DECLARE @TableB  table (RowID int, TypeOf varchar(10))
INSERT INTO @TableA VALUES (1,'aaaaa','A')
INSERT INTO @TableA VALUES (2,'bbbbb','B')
INSERT INTO @TableA VALUES (3,'ccccc','C')
INSERT INTO @TableB VALUES (1,'wood')
INSERT INTO @TableB VALUES (2,'wood')
INSERT INTO @TableB VALUES (2,'steel')
INSERT INTO @TableB VALUES (2,'rock')
INSERT INTO @TableB VALUES (3,'plastic')
INSERT INTO @TableB VALUES (3,'paper')


;WITH Combined AS
(
SELECT
    a.RowID,a.Value1,a.Value2,b.TypeOf
    FROM @TableA                 a
        LEFT OUTER JOIN @TableB  b ON a.RowID=b.RowID

)
SELECT
    a.*,dt.CombinedValue
    FROM @TableA        a
        LEFT OUTER JOIN (SELECT
                             c1.RowID
                                 ,STUFF(
                                            (SELECT
                                                 ', ' + TypeOf
                                                 FROM Combined  c2
                                                 WHERE c2.rowid=c1.rowid
                                                 ORDER BY c1.RowID, TypeOf
                                                 FOR XML PATH('') 
                                            )
                                            ,1,2, ''
                                       ) AS CombinedValue
                             FROM Combined c1
                             GROUP BY RowID
                        ) dt ON a.RowID=dt.RowID

OUTPUT:

RowID       Value1 Value2 CombinedValue
----------- ------ ------ ------------------
1           aaaaa  A      wood
2           bbbbb  B      rock, steel, wood
3           ccccc  C      paper, plastic
KM.
  • 101,727
  • 34
  • 178
  • 212
  • I'm not sure how to adapt this to my query; I played around with it and couldn't get the required results. I ended up deciding to manually build a datatable and load it into a dataset to use in the method I have for flipping dataset orientation. – Geo Ego Mar 01 '10 at 17:22
1

"Flipping" dataset can be done in sql, for example see h@@p://stackoverflow.com/questions/2344590/how-do-i-transform-rows-into-columns-in-sql-server-2005 But I do agree that often times it's simpler to do this in C#

What KM suggested is expanded on in this article: http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/

Andrew Savinykh
  • 25,351
  • 17
  • 103
  • 158