我有3个具有一对多关系的表。 比方说订单和订单商品。商品具有产品代码,例如a,b,c,d等...
系统中大约有15种不同的产品代码。
加入后,我需要对数据进行透视处理,以使订单和产品代码与同一行相同,并且只需将产品代码隐式转换为布尔标志(即1或0)即可。
我知道我可以使用自我连接15次或在SELECT中使用查找功能
IIF((select DISTINCT 1 from <product code table> where code = 'a' and <join from order item table>) is null, 0, 1)
(每个产品代码)。
这样做不是很好的表现。所以我想知道是否有更好的方法来使用PIVOT,CROSS APPLY或其他方法。
尝试了查询,它可以工作,但跳跳是一种更好的方法。
SELECT
order_id,
order_item_id,
IIF((select DISTINCT 1 from product_codes c where code = 'a' and i.item_product_code_id = c.product_code_id) is null, 0, 1) as a,
IIF((select DISTINCT 1 from product_codes c where code = 'b' and i.item_product_code_id = c.product_code_id) is null, 0, 1) as b,
IIF((select DISTINCT 1 from product_codes c where code = 'c' and i.item_product_code_id = c.product_code_id) is null, 0, 1) as c,
IIF((select DISTINCT 1 from product_codes c where code = 'd' and i.item_product_code_id = c.product_code_id) is null, 0, 1) as d,
IIF((select DISTINCT 1 from product_codes c where code = 'f' and i.item_product_code_id = c.product_code_id) is null, 0, 1) as e,
IIF((select DISTINCT 1 from product_codes c where code = 'g' and i.item_product_code_id = c.product_code_id) is null, 0, 1) as f,
IIF((select DISTINCT 1 from product_codes c where code = 'h' and i.item_product_code_id = c.product_code_id) is null, 0, 1) as g,
FROM orders o INNER JOIN order_items i ON o.order_id = i.order_id
这里是样本。左侧是查询结果的样子,右侧是所需的结果。(我还无法在其中发布图片)