连接 SQL 查询中一个字段的多个结果

发布于 2024-08-23 06:20:37 字数 2645 浏览 9 评论 0原文

我不确定这是否可以通过 SQL 查询实现,但我会尝试一下。

我正在用 C# 开发一个 SharePoint Web 部件,它连接到 SQL 数据库并运行查询,然后将该结果集数据绑定到网格视图。它工作正常,但我有一个小障碍。在大多数情况下,我的查询将为每个字段返回一个结果。我垂直显示信息,所以它看起来大致是这样的:

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                   Cardstock

理想情况下,我想最终结果会是这样的:

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

另一个可接受的结果可能如下所示,添加几列但只返回多个结果这些领域:

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                             

我愿意接受任何建议。如果可能的话,我想将其包含在结果集中,而不需要单独的查询。下面是我用来提取数据的代码:

                    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);

我会列出我的 SQL 查询,但它非常庞大。我现在正在拉入一百多个字段,其中包含大量 SUBSTRING 格式和连接,因此这会浪费空间,但这实际上是一个相当简单的查询,我使用 AS 语句选择字段来获取我想要的名称,并使用一些 LEFT JOIN 来提取我需要的数据,而无需进行多次查询。产品/材料表的架构如下所示:

fldMachineID
fldProductType
fldSteel
fldWood
fldPaper

显然,每个客户都有多个条目,每个条目对应不同的 fldProductType 值。如果我遗漏了什么,我可以添加它。感谢大家的时间和帮助!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

祁梦 2024-08-30 06:20:37

试试这个:

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

输出:

RowID       Value1 Value2 CombinedValue
----------- ------ ------ ------------------
1           aaaaa  A      wood
2           bbbbb  B      rock, steel, wood
3           ccccc  C      paper, plastic

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
太阳公公是暖光 2024-08-30 06:20:37

“翻转”数据集可以在sql中完成,例如参见h@@p://stackoverflow.com/questions/2344590/how-do-i-transform-rows-into-columns-in-sql-server-2005
但我确实同意,通常在 C# 中执行此操作会更简单

KM 建议的内容在本文中进行了扩展:http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql /

"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/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文