在sql语句中创建一个包

时间:2014-05-23 14:35:27

标签: sql sql-server tsql

我需要在Part_id上创建一个包。对于每个包P1,P2,P3,...... 如果在P1中有一个true,那么我需要在package_code中包含代码,如图所示,对于描述我需要在sql语句中执行此操作。

Part_id code    Code_description    P1      P2      P3      P4      P5      P6      P7      P8      P9      P10     P11     P12     P13     P14     P15
85      19      D1                  TRUE    TRUE    FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE
85      34      D2                  TRUE    TRUE    FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE
85      CS      D3                  TRUE    FALSE   TRUE    FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE
85      EP      D4                  TRUE    FALSE   TRUE    FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE
85      MS      D5                  TRUE    FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE
85      XR      D6                  TRUE    FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE
85      BU      D7                  TRUE    TRUE    TRUE    FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE







 Packages   Part_id     Package_code                    Package_description 
 P1         85          19| 34| CS | EP | MS |XR |BU    D1 |  D2 | D3| D4 |D5|D6 |D7 
 P2         85          19|34|BU                        D1| D2 | D7 
 P3         85          CS|EP                           D3 |  D4

1 个答案:

答案 0 :(得分:1)

首先,这是一个糟糕的桌面设计,但我假设你无法控制它。

获得所需结果的第一步是将P列取消,以便将它们视为行(我只去了P4。我会留给你填写其余部分)。我将结果放入CTE。

with CTE(Part_id, code, Code_description, Package, Included) as
(
select Part_id, code, Code_description, Package, Included
from Part p
unpivot
(Included for Package in (P1, P2, P3, P4)) unpvt
)

下一个技巧是在CTE行中创建一个分隔的代码列表(基于Included字段)。这是这样做的:

STUFF((select ' | ' + c2.code from cte c2 where c2.Package = c.Package and c2.Part_id = c.Part_id and c2.Included = 1 order by c2.Code_description for XML PATH('')), 1, 3, '')

是的,这很难看,但SQL Server并没有真正设计用来做这类事情。

最终查询如下所示

select distinct c.Package, 
c.Part_id, 
STUFF((select ' | ' + c2.code from cte c2 where c2.Package = c.Package and c2.Part_id = c.Part_id and c2.Included = 1 order by c2.Code_description for XML PATH('')), 1, 3, '') Package_code,
STUFF((select ' | ' + c2.Code_description from cte c2 where c2.Package = c.Package and c2.Part_id = c.Part_id and c2.Included = 1 order by c2.Code_description for XML PATH('')), 1, 3, '') Package_description
from cte c

这是SQL Fiddle