所以,假设我有表Product
:
ProdID | ProdDesc
-----------------
1 | Widget
2 | Snikt Spring
3 | Water Bearing
和表ProdFeature
ProdID | DocID | ProdSafe | ProdShiny
-------------------------------------
1 | 34 | Y | Null
1 | 17 | Null | Y
2 | 54 | Y | Null
3 | 2 | Null | Y
我如何获得如下结果:
ProdID | ProdSafe | SafetyDocID | ProdShiny | ShinyDocID
--------------------------------------------------------
1 | Y | 34 | Y | 17
感谢任何帮助。 〜 - [R
答案 0 :(得分:0)
那样的东西?
SELECT p.ProdID,
pf1.ProdSafe,
pf1.DocID SafetyDocID,
pf2.ProdShiny,
pf2.DocID ShinyDocID
FROM Product p
left outer join ProdFeature pf1
on p.ProdID = pf1.ProdID and pf1.ProdSafe is not null
left outer join ProdFeature pf2
on p.ProdID = pf2.ProdID and pf2.ProdShiny is not null
另一个版本性能较差:
SELECT p.ProdID,
(select ProdSafe
from ProdFeature
where ProdID = p.ProdID
and ProdSafe is not null) ProdSafe,
(select DocID
from ProdFeature
where ProdID = p.ProdID
and ProdSafe is not null) SafetyDocID,
(select ProdShiny
from ProdFeature
where ProdID = p.ProdID
and ProdShiny is not null) ProdShiny,
(select DocID
from ProdFeature
where ProdID = p.ProdID
and ProdShiny is not null) ShinyDocID
FROM Product p