SQL选择不同列必须相等的地方

时间:2019-04-23 13:38:43

标签: sql-server

我需要联接2个表,其中主键是“引用”。

UAP =生产统一

第一个表具有每周的UAP消耗率

AUTO.D805DATPOR.TRP060H

第二张表具有UAP可用库存,但是,在每张表中,UAP的名称不同,但名称相同。

AUTO.D805DATPOR.IC130M

例如,在第一个表上,我有UAP1,在第二个表上,这叫做M1,所以基本上是关联

Table1       Table2

UAP1    -    M1
UAP2    -    M2
UAP3    -    M3
UAP4    -    M4
UAP5    -    M5
UAP6    -    M6
UAPP    -    Protos
EXT     -    EXTR

这是到目前为止的查询

SELECT 
    Reference, 
    UAP, 
    CAST(W01 AS Float) AS W01, 
    CAST(W02 AS Float) AS W02, 
    CAST(W01 / 5 AS Float) AS DailyW01, 
    CAST(W02 / 5 AS Float) AS DailyW02, 
    CAST(Stock as Float) AS Stock 
FROM OPENQUERY(MACPAC, 
    'SELECT 
        A.RH6001 as Reference, 
        A.RH6002 as UAP, 
        A.RH6030 as W01, 
        A.RH6031 as W02,
        S.LLBLT1 AS Stock
    FROM AUTO.D805DATPOR.TRP060H AS A
    LEFT JOIN  AUTO.D805DATPOR.IC130M AS S
    ON A.RH6001 = S.LLPPN 
    WHERE (A.RH6001 Not Like ''FS%'')
    AND S.LLBLT1 <> 0') 

我只需要按参考某种方式对记录进行分组,并显示每个UAP所属的正确库存。如果名称相同但不同,这将很容易。

是否有一种无需大量IF子句即可处理此问题的方法?

这是分开的查询

SELECT * FROM OPENQUERY(MACPAC, 
    'SELECT 
        IC130M.LLPPN AS Referencia, 
        IC130M.LLSTLC AS UAP, 
        IC130M.LLBLT1 AS Stock
    FROM AUTO.D805DATPOR.IC130M IC130M
    WHERE IC130M.LLSTLC IN (''M1'',''M2'',''M3'',''M4'',''M5'',''M6'',''EXTR'',''PROTOS'') 
    AND IC130M.LLBLT1 <> 0 
    ORDER BY IC130M.LLSTLC ASC, IC130M.LLBLT1 DESC')

这将返回此

enter image description here

,这里是每周消费表

    SELECT * FROM OPENQUERY(MACPAC, 
        'SELECT TRP060H.RH6001 as Referencia, 
                TRP060H.RH6002 as UAP, 
                TRP060H.RH6030 as W01, 
                TRP060H.RH6031 as W02
    FROM AUTO.D805DATPOR.TRP060H TRP060H
    WHERE (TRP060H.RH6001 Not Like ''FS%'') ')

enter image description here

1 个答案:

答案 0 :(得分:1)

解决此问题的最佳方法是简单地添加一个关系表。换句话说,从中创建一个新的永久表,并将其用于联接两个表:

UAP1    -    M1
UAP2    -    M2
UAP3    -    M3
UAP4    -    M4
UAP5    -    M5
UAP6    -    M6
UAPP    -    Protos
EXT     -    EXTR