如何将列单位添加到@header per row have flag allow 1?

smtd7mpg  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(295)

我正在处理sql server 2012的查询。我有一个问题:我不能将列单位添加到 @Header .
当临时表中的行 #nonparametric 有国旗吗 Allow 设置为1时,每个单元必须有两列。
这里我有标志允许设置为1每个家庭和参数化,所以它必须声明 @Header .
有parametricunit,familyunit,因为我在temp表上为parametric和family设置了标志allow=1
非参数温度表。
表#nonparametric的另一个含义是我将得到所有dkfeaturename have标志allow 0将有一个
列,但dkfeaturename have flag allow=1将在每个单元上有额外的列,它的名称将是变量@header上的column+'unit'。

create table #nonparametricdata
(
PART_ID nvarchar(50) ,
CompanyName  nvarchar(50),
PartNumber nvarchar(50),
DKFeatureName nvarchar(100),
Tempvalue nvarchar(50),
FlagAllow bit
)

insert into #nonparametricdata
values
('1222','Honda','silicon','package','15.50Am',0),
('1900','MERCEIS','GLASS','family','90.00Am',1),--have column per Unit on @Header because FlagAllow=1
('5000','TOYOTA','alominia','source','70.20kg',0),
('8000','MACDA','motor','parametric','50.40kg',1),--have column per Unit on @Header because FlagAllow=1
('8900','JEB','mirror','noparametric','75.35kg',0)

create table #FinalTable
(
DKFeatureName  nvarchar(50),
DisplayOrder  int
)

insert into #FinalTable (DKFeatureName,DisplayOrder) 
values 
('package',3),
('family',4),
('source',5),
('parametric',2),
('noparametric',1)

我的尝试如下:

DECLARE @Header NVARCHAR(MAX)
SELECT
    @Header = STUFF(
        (
            SELECT ', ' + QUOTENAME (DKFeatureName)
            FROM #FinalTable
            ORDER BY DisplayOrder
            FOR XML PATH ('')
        ),1,2,''
    )
    select @Header

预期结果是:

[noparametric], [parametric],[parametricUnit], [package], [family],[familyUnit], [source]
wsewodh2

wsewodh21#

有点像黑客,但是通过使用一个连接和一个简单的case
例子

DECLARE @Header NVARCHAR(MAX)
SELECT
    @Header = STUFF(
        (
            SELECT ', ' + quotename(A.DKFeatureName) + case when B.FlagAllow = 1 then ','+quotename(A.DKFeatureName+'Unit') else '' end
            FROM #FinalTable A
            Join #nonparametricdata B on A.DKFeatureName=B.DKFeatureName
            ORDER BY DisplayOrder
            FOR XML PATH ('')
        ),1,2,''
    )
    select @Header

退货

[noparametric], [parametric], [parametricUnit], [package], [family], [familyUnit], [source]

编辑。
你可能想要改变

Join #nonparametricdata B on A.DKFeatureName=B.DKFeatureName

Join (Select distinct DKFeatureName,FlagAllow 
       From #nonparametricdata 
     ) B on A.DKFeatureName=B.DKFeatureName

相关问题