0

我们正在尝试自动化一些步骤,我需要设置一个查询来按计划转储数据。我遇到的问题是从 SQL 表中获取单行数据并将其转储到多行数据中。SQL 表用于零件订购单,具有最多可输入 10 个零件的字段 (Part01 - Part10) 和每个零件的数量字段 (Qty01-Qty10)。和大多数订单一样,我们不会在每个订单上使用全部 10 行,所以在导出时,我们还需要测试 part 字段 (PartXX<>'') 中是否有数据,以便只为实际有的行生成行数据。表中还有一些字段需要填充到每个输出行中,即使它没有更改。第一个“行”的查询是直截了当的,但我的障碍是“IF/THEN”

我正在寻找的输出是这样的:

Ticket# CustID Account Line ShipAttn ShipAdd ShipCity ShipState ShipZip 部件数量
123456 Cust01 987465 1 Joe Smith 地址 AnyTown IL 01234 Key 2
123456 Cust01 987456 2 Joe Smith 地址 AnyTown IL 01234 锁 2

任何方向表示赞赏。

4

3 回答 3

0

不知道您的确切架构,您可能会尝试这样的事情来取消您的记录:

;with cte as (
    -- Select for each Part/Qty:
    select Ticket#, CustID, Account, ShipAttn, ShipAdd, ShipCity, ShipState, ShipZip, Part01 as Part, Qty01 as Qty, 1 as Line
    from Orders
    where Part01 is not null and Qty01 is not null
    union all
    select Ticket#, CustID, Account, ShipAttn, ShipAdd, ShipCity, ShipState, ShipZip, Part02 as Part, Qty02 as Qty, 2 as Line -- 02!
    from Orders
    where Part02 is not null and Qty02 is not null -- 02!
    union all
    select Ticket#, CustID, Account, ShipAttn, ShipAdd, ShipCity, ShipState, ShipZip, Part03 as Part, Qty03 as Qty, 3 as Line -- 03!
    from Orders
    where Part03 is not null and Qty03 is not null -- 03!
    --union all...keep going with 04 - 10
)
select Ticket#, CustID, Account
    , row_number() over (partition by Ticket# order by Line) as Line
    , ShipAttn, ShipAdd, ShipCity, ShipState, ShipZip, Part, Qty
from cte
order by Ticket#, Line
于 2013-02-06T18:19:06.820 回答
0

您正在寻找的是数据透视表(或“交叉表”)。每个 RDBMS 都有自己的解决方案,您没有提供自己的解决方案。确切的语法还取决于您的 RDBMS。

标准 SQL查询可能如下所示:

SELECT Ticket#, CustID, Account, 1 AS Line, ShipAttn, ShipAdd, ShipCity, ShipState, ShipZip, Part01 AS Part, Qty01 AS Qty
FROM   tbl
WHERE  Part01 IS NOT NULL

UNION ALL
SELECT Ticket#, CustID, Account, 2 AS Line, ShipAttn, ShipAdd, ShipCity, ShipState, ShipZip, Part02 AS Part, Qty02 AS Qty
FROM   tbl
WHERE  Part02 IS NOT NULL

UNION ALL ...

ORDER BY Ticket#, CustID, Account, Line

ORDER BY应用于完整的结果,而不仅仅是查询的最后一段。因此,您不需要子选择或 CTE。

于 2013-02-06T18:19:55.037 回答
0

上述两种解决方案都需要联合,因为您使用的是 SQL Server 2008 R2,您可能想要使用 UnPivot 的内置功能......它仍然未经测试,但它应该可以工作。

它基于描述的解决方案:http: //mangalpardeshi.blogspot.com/2009/04/unpivot-multiple-columns.html

SELECT Ticket#, CustID, Account
    , row_number() over (partition by Ticket# order by Parts) as Line
    , ShipAttn, ShipAdd, ShipCity, ShipState, ShipZip, Part, Qty 
FROM 
( 
SELECT Ticket#, CustID, Account , ShipAttn, ShipAdd, ShipCity, ShipState, ShipZip,
       Part01, Part02, Part03, Part04, Part05, Part06, Part07, Part08, Part09, Part10,
       Qty01, Qty02, Qty03, Qty04, Qty05, Qty06, Qty07, Qty08, Qty09, Qty10
FROM Suppliers 
) Main
UNPIVOT 
( 
Part FOR Parts IN (Part01, Part02, Part03, Part04, Part05, Part06, Part07, Part08, Part09, Part10) 
) P


UNPIVOT 
( 
Qty For Qtys IN (Qty01, Qty02, Qty03, Qty04, Qty05, Qty06, Qty07, Qty08, Qty09, Qty10) 
) Q

WHERE RIGHT(Parts,2) =  RIGHT(Qtys,2)
于 2013-02-07T21:01:36.403 回答