如何根据属性表填充布尔列?
Posted
技术标签:
【中文标题】如何根据属性表填充布尔列?【英文标题】:How do you populate boolean columns based on a table of properties? 【发布时间】:2021-03-08 22:13:01 【问题描述】:我有一个名为 Product 的表,其中包含一个产品标识号和一个与该产品标识号关联的 ID。
pin id
11 10
12 11
13 12
我还有一个带有 id 和 property_id 的属性表
id property_id
10, 108
11, 109
12, 200
108 指属性 isNew,109 指属性 isPremium,200 指属性 isExclusive。
有了这些,我想创建这个临时表:
pin id isNew isPremium isExclusive
11 10 1 0 0
12 11 0 1 0
13 12 0 0 1
我该怎么做?您可以轻松地创建一个临时表,但我不确定如何映射这些值。
【问题讨论】:
【参考方案1】:您可以使用 PIVOT 函数来获得您想要的结果。
DECLARE @product table(pin int, id int)
DECLARE @property table(id int, property_id int)
insert into @product
values
(11 ,10),
(12 ,11),
(13 ,12);
insert into @property
values
(10, 108),
(11, 109),
(12, 200);
SELECT pvt.pin, pvt.product_id, [108] as is_new,[109] as is_premium, [200] as is_exclusive
FROM
(SELECT p.pin, p.id, pr.id as product_id, pr.property_id
FROM @Product as p
INNER JOIN @Property as pr
ON pr.id = p.id) as t
PIVOT
(
COUNT(t.id)
for t.Property_Id in ([108],[109],[200])
) as pvt
+-----+------------+--------+------------+--------------+
| pin | product_id | is_new | is_premium | is_exclusive |
+-----+------------+--------+------------+--------------+
| 11 | 10 | 1 | 0 | 0 |
| 12 | 11 | 0 | 1 | 0 |
| 13 | 12 | 0 | 0 | 1 |
+-----+------------+--------+------------+--------------+
【讨论】:
【参考方案2】:你可以做条件聚合:
select pt.pin, pt.id,
max(case when py.property_id = 108 then 1 else 0 end) as is_new,
max(case when py.property_id = 109 then 1 else 0 end) as is_premium,
max(case when py.property_id = 200 then 1 else 0 end) as is_exclusive
from product pt
inner join property py on py.id = pt.id
group by pt.pin, pt.id
这假设每个产品可能有多个属性 - 与您的示例数据中显示的不同。如果不是这种情况,则不需要聚合:
select pt.pin, pt.id,
case when py.property_id = 108 then 1 else 0 end as is_new,
case when py.property_id = 109 then 1 else 0 end as is_premium,
case when py.property_id = 200 then 1 else 0 end as is_exclusive
from product pt
inner join property py on py.id = pt.id
【讨论】:
以上是关于如何根据属性表填充布尔列?的主要内容,如果未能解决你的问题,请参考以下文章
如何根据excel中的另一个单元格值自动填充两个不同列中的数据