我有两张桌子:
一个是促销
| PromoId |Promo Decription|
----------------------
| 101 | abc|
| 102 | pqr|
| 103 | alp|
| 104 | adc|
| 201 | abc|
,另一个是PromotionType
| PromoId | PromoType |
----------------------
| 101 | 1 |
| 121 | 2 |
| 188 | 3 |
| 104 | 4 |
| 191 | 4 |
| 102 | 4 |
我想要一个结果表
| PromoId | Flag |Promo Decription |PromoType |
----------------------
| 101 | 1 | | 1 |
| 121 | 0 | | 2 |
| 188 | 0 | | 3 |
| 104 | 1 | adc | 4 |
| 191 | 0 | | 4 |
| 102 | 1 | pqr | 4 |
| 103 | 1 | alp | |
| 201 | 0 | abc | |
即我想要一个结果表,它是两个表的并集。它不应该包含重复值,并且对于两个表共有的PromoId的所有值,flag的值都设置为true。
我使用的是Sql Server作为我们的数据库。
答案 0 :(得分:2)
您可以使用FULL OUTER JOIN
执行此操作:
select
coalesce(p.promoid, t.promoid) promoid,
case when p.promoid = t.promoid then 1 else 0 end flag
from promotion p
full outer join promotiontype t
on p.promoid = t.promoid
order by promoid
结果:
| PROMOID | FLAG |
------------------
| 101 | 1 |
| 102 | 1 |
| 103 | 0 |
| 104 | 1 |
| 121 | 0 |
| 188 | 0 |
| 191 | 0 |
| 201 | 0 |
编辑,即使您对数据样本进行了更改,查询仍会产生结果:
select
coalesce(p.promoid, t.promoid) promoid,
case when p.promoid = t.promoid then 1 else 0 end flag,
isnull(p.[Promo Decription], '') [Promo Decription],
isnull(t.PromoType, null) PromoType
from promotion p
full outer join promotiontype t
on p.promoid = t.promoid
order by
case when PromoType is not null then 0 else 1 end, promotype, promoid
结果是:
| PROMOID | FLAG | PROMO DECRIPTION | PROMOTYPE |
-------------------------------------------------
| 101 | 1 | abc | 1 |
| 121 | 0 | | 2 |
| 188 | 0 | | 3 |
| 102 | 1 | pqr | 4 |
| 104 | 1 | adc | 4 |
| 191 | 0 | | 4 |
| 103 | 0 | alp | (null) |
| 201 | 0 | abc | (null) |
答案 1 :(得分:0)
您可以使用以下脚本:
select a.PromoID,
coalesce((case when b.promoID=a.promoID then '1'
when b.promoID<>a.promoID then '0'
end),'0') flag
from hr.promotion_type a
LEFT OUTER join hr.promotion b
on(a.promoID= b.promoid)
这里,HR是我使用的架构,您可以使用相应的架构