如何选择有条件的联合结果

时间:2019-05-10 16:21:35

标签: sql-server select distinct union

如果有两个具有状态寄存器的供应商未注册,那么我想选择不同的供应商,然后选择一个具有状态寄存器的供应商,但是如果只有一个供应商,则只需选择它,

我正在使用SQL Server 2017

SELECT
 pv.vendor_id,pv.vendor_name,'Not Registered' as registration_status
    FROM 
        proposal_vendor as pv
    UNION
SELECT      bv.vendor_id,bv.vendor_name,bv.registration_status
    FROM 
        bidding_vendor as bv
    WHERE 
        bv.bidding_header_id = 97

48  vendor a               Register
48  vendor a           Not Registered   
4110    vendor b               Register
4110    vendor b               Not Registered   
4197    vendor c               Not Registered   

我期望的是

48  vendor a        Register
4110    vendor b            Register
4197    vendor c        Not Registered

3 个答案:

答案 0 :(得分:2)

您可以使用行号和case语句获得预期的输出。如果您有两个注册,则可以使用等级,否则,如果每个供应商ID仅需要一行,则可以使用行号。

select vendor_id, vendor_name, registration_status from  (
SELECT      bv.vendor_id,bv.vendor_name,bv.registration_status, row_number() over (partition by bv.vendor_id order by case when registration_status = 'Register' then 1 else 2) rownum 
    FROM 
        bidding_vendor as bv) t
where t.rownum = 1 

答案 1 :(得分:1)

SELECT pv.vendor_id,
       pv.vendor_name,
       'Not Registered' as registration_status
    FROM proposal_vendor as pv
    WHERE NOT EXISTS(SELECT 1
                         FROM bidding_vendor bv
                         WHERE bv.vendor_id = pv.vendor_id
                             AND bv.bidding_header_id = 97)
UNION ALL
SELECT bv.vendor_id,
       bv.vendor_name,
       bv.registration_status
    FROM bidding_vendor as bv
    WHERE bv.bidding_header_id = 97

答案 2 :(得分:1)

这里有多种可能性。

您可以将主查询作为结果查询的派生表源

SELECT pv.vendor_id, 
    pv.vendor_name, MAX(registration_status) as registration_status
FROM (
    SELECT
     pv.vendor_id,pv.vendor_name,'Not Registered' as registration_status
        FROM 
            proposal_vendor as pv
        UNION
    SELECT      bv.vendor_id,bv.vendor_name,bv.registration_status
        FROM 
            bidding_vendor as bv
        WHERE 
            bv.bidding_header_id = 97
    ) src

您可以使用外部联接逻辑

SELECT pv.vendor_id, 
    pv.vendor_name, 
    CASE WHEN bv.vendor_id is null
        THEN 'Not '
    END + 'Registered' as registration_status
FROM proposal_vendor as pv
FULL OUTER JOIN bidding_vendor as bv
    ON pv.vendor_id = bv.vendor_id
WHERE pv.vendor_id = 97
    OR bv.vendor_id = 97

或者您可以从六种不同的技术中选择另一个。