避免多个连接

时间:2017-07-28 14:50:43

标签: sql sql-server

我有一张桌子(制造商):

Manufacturer    ID
------------------
Lagun            1
Hurco            2
Mazak            3
Haas             4

然后是另一张表(库存):

Shop     Lathe    DrillPress    CNC    Mill    ID
-------------------------------------------------
ABC Inc    2          1           3      3       1
VECO       4          2           1      2       2

我最终需要:

Shop     Lathe    DrillPress   CNC     Mill
--------------------------------------------  
ABC Inc  Hurco    Lagun        Mazak   Mazak
VECO     Haas     Hurco        Lagun   Hurco

我有这个:

SELECT 
     Shop, M1.Manufacturer AS Lathe, M2.Manufacturer AS DrillPress, 
     M3.Manufacturer AS CNC, M4.Manufacturer AS Mill 
FROM Inventory I
LEFT JOIN Manufacturers M1 ON M1.ID = I.LstFlowMan
LEFT JOIN Manufacturers M2 ON M2.ID = I.LstFiltFlowMan
LEFT JOIN Manufacturers M3 ON M3.ID = I.LstFilterMan
LEFT JOIN Manufacturers M4 ON M4.ID = I.LstEmitMan

我可能错过了使用PIVOT或CROSS APPLY或其他东西的更好方法。

3 个答案:

答案 0 :(得分:2)

这是一种方法。

SELECT i.shop, 
       lathe = Max(CASE WHEN i.lathe = m.id THEN m.manufacturer END), 
       drillpress = Max(CASE WHEN i.drillpress = m.id THEN m.manufacturer END), 
       mill = Max(CASE WHEN i.mill = m.id THEN m.manufacturer END),
       cnc = Max(CASE WHEN i.cnc= m.id THEN m.manufacturer END)
FROM   manufacturers m 
       JOIN inventory i 
         ON m.id IN ( i.lathe, i.drillpress, i.cnc, i.mill ) 
GROUP  BY i.shop 

考虑更改inventory表的表结构。

广告资源 Shop,MachineType,ManufacturerID

然后你可以使用Pivot / Cross选项卡来获得结果

答案 1 :(得分:2)

你可以UNPIVOT JOIN和RE-PIVOT

SELECT * FROM (
select SHOP, KEYS, MANUFACTURER from
 inventory unpivot ( val for keys in ("LATHE","DRILLPRESS","CNC","MILL"))
 JOIN Manufacturers M ON M.ID=VAL
) PIVOT (
MAX(MANUFACTURER)
FOR keys in ('LATHE','DRILLPRESS','CNC','MILL')
)

答案 2 :(得分:2)

感谢@LauDec,这是SQLServer版本:

select * from (
select SHOP, KEYS, MANUFACTURER from
(select SHOP, LATHE,DRILLPRESS,CNC,MILL from inventory) a
    unpivot (val for keys in (LATHE,DRILLPRESS,CNC,MILL)) as unpvt
     JOIN Manufacturers M ON M.ID=VAL
) a
PIVOT (
MAX(MANUFACTURER)
FOR keys in (LATHE,DRILLPRESS,CNC,MILL)
) as pp