根据另一列值将一列值拆分为多列
split one column values into multiple column based another column value
能否请您帮我编写 select 查询以获得下图中的预期输出。我想要的是根据其 UOM 列值 ZF2、ZF1 和 ZF3 分别将 UPC 列值拆分为三列(Bottle UPC、Pack UPC、Case UPC)。
如有任何帮助,我们将不胜感激。谢谢!
您可以使用三个查询来分隔列并使用 UNION ALL 将它们连接起来。然后我们使用 max 只保留我们想要的那个。
我知道这与您显示的格式不完全相同,但它确实包含所有信息而没有重复。
Select
Material_id,
UOM,
Max(Bottle) as Bottle_UPC,
Max(Pack) as Pack_UPC,
Max(Case) as Case_UPC
From
(
Select
Material_id,
UOM,
UPC as Bottle,
'' as Pack,
'' as Case
From table_name
Where UOM = 'ZF1'
Union all
Select
Material_id,
UOM,
'' ,
UPC ,
''
From table_name
Where UOM = 'ZF2'
Union all
Select
Material_id,
UOM,
'' ,
'' ,
UPC
From table_name
Where UOM = 'ZF3'
)
Group by
Material_id,
UOM,
这是获得所需准确结果的一种方法,但令人困惑的是,为什么您希望所有三行都返回您已经仅转置到第一行的值...
;WITH cte AS
(
SELECT *, rn = ROW_NUMBER() OVER (PARTITION BY Material_ID ORDER BY UOM),
bupc = CASE WHEN UOM = 'ZF2' THEN UPC END,
pupc = CASE WHEN UOM = 'ZF1' THEN UPC END,
cupc = CASE WHEN UOM = 'ZF3' THEN UPC END
FROM dbo.SomeTableName AS s
),
agg AS
(
SELECT Material_ID,
bupc = MAX(bupc),
pupc = MAX(pupc),
cupc = MAX(cupc)
FROM cte GROUP BY Material_ID
)
SELECT cte.Material_ID, cte.UOM,
[Bottle UPC] = COALESCE(agg.bupc, ''),
[Pack UPC] = COALESCE(agg.pupc, ''),
[Case UPC] = COALESCE(agg.cupc, '')
FROM cte
LEFT OUTER JOIN agg ON agg.Material_ID = cte.Material_ID
AND cte.rn = 1;
能否请您帮我编写 select 查询以获得下图中的预期输出。我想要的是根据其 UOM 列值 ZF2、ZF1 和 ZF3 分别将 UPC 列值拆分为三列(Bottle UPC、Pack UPC、Case UPC)。
如有任何帮助,我们将不胜感激。谢谢!
您可以使用三个查询来分隔列并使用 UNION ALL 将它们连接起来。然后我们使用 max 只保留我们想要的那个。
我知道这与您显示的格式不完全相同,但它确实包含所有信息而没有重复。
Select
Material_id,
UOM,
Max(Bottle) as Bottle_UPC,
Max(Pack) as Pack_UPC,
Max(Case) as Case_UPC
From
(
Select
Material_id,
UOM,
UPC as Bottle,
'' as Pack,
'' as Case
From table_name
Where UOM = 'ZF1'
Union all
Select
Material_id,
UOM,
'' ,
UPC ,
''
From table_name
Where UOM = 'ZF2'
Union all
Select
Material_id,
UOM,
'' ,
'' ,
UPC
From table_name
Where UOM = 'ZF3'
)
Group by
Material_id,
UOM,
这是获得所需准确结果的一种方法,但令人困惑的是,为什么您希望所有三行都返回您已经仅转置到第一行的值...
;WITH cte AS
(
SELECT *, rn = ROW_NUMBER() OVER (PARTITION BY Material_ID ORDER BY UOM),
bupc = CASE WHEN UOM = 'ZF2' THEN UPC END,
pupc = CASE WHEN UOM = 'ZF1' THEN UPC END,
cupc = CASE WHEN UOM = 'ZF3' THEN UPC END
FROM dbo.SomeTableName AS s
),
agg AS
(
SELECT Material_ID,
bupc = MAX(bupc),
pupc = MAX(pupc),
cupc = MAX(cupc)
FROM cte GROUP BY Material_ID
)
SELECT cte.Material_ID, cte.UOM,
[Bottle UPC] = COALESCE(agg.bupc, ''),
[Pack UPC] = COALESCE(agg.pupc, ''),
[Case UPC] = COALESCE(agg.cupc, '')
FROM cte
LEFT OUTER JOIN agg ON agg.Material_ID = cte.Material_ID
AND cte.rn = 1;