从SQL中的多个表中获取匹配的值

时间:2019-05-23 14:22:52

标签: sql sql-server

我有6个具有客户ID的表。 是否有可能在一个查询中获得所有表中都相同的客户ID? 在我的示例中,结果的客户ID是8和9 (必须考虑到,实际上任何表都可能具有或没有值)

非常感谢 最好的问候

DECLARE @TCustomerAge  TABLE(
CustomerID  INT not null ); 


DECLARE @TCustomerLocalization  TABLE(
CustomerID  INT not null ); 


DECLARE @TCustomerGroup  TABLE(
CustomerID  INT not null ); 


DECLARE @TCustomerStore  TABLE(
CustomerID  INT not null ); 


DECLARE @TCustomerSales  TABLE(
CustomerID  INT not null ); 


DECLARE @TCustomerPayment  TABLE(
CustomerID  INT not null ); 


--@TCustomerAge empty
insert into @TCustomerLocalization values (8), (9), (11)
insert into @TCustomerGroup values (8), (9), (10), (11)
insert into @TCustomerStore values (8), (9), (11)
--@@TCustomerSales empty
insert into @TCustomerPayment values (2), (3), (5), (8), (9), (10)

-- Result -> 8, 9

2 个答案:

答案 0 :(得分:2)

要处理空表,也许使用union是更好的方法:

with t as (
      select id, '@TCustomerAge' as tablename from @TCustomerAge 
      union  -- uses union to remove duplicates within tables
      select id, '@TCustomerLocalization' from @TCustomerLocalization
      union
      . . .
     )
select t.id
from t cross join
     (select count(distinct tablename) as n from t) n
group by t.id, n.n
having count(*) = n.n;

空表未在t中表示,因此count(distinct)仅对存在的表进行计数。

答案 1 :(得分:0)

;with CteAllIDs as (
    SELECT CustomerID FROM @TCustomerAge UNION
    SELECT CustomerID FROM @TCustomerLocalization UNION
    SELECT CustomerID FROM @TCustomerGroup UNION
    SELECT CustomerID FROM @TCustomerStore UNION
    SELECT CustomerID FROM @TCustomerSales UNION
    SELECT CustomerID FROM @TCustomerPayment
)
SELECT CteAllIDs.CustomerID
FROM CteAllIDs
WHERE (EXISTS (SELECT * FROM @TCustomerAge WHERE CustomerID = CteAllIDs.CustomerID) 
    OR NOT EXISTS (SELECT * FROM @TCustomerAge))
AND (EXISTS (SELECT * FROM @TCustomerLocalization WHERE CustomerID = CteAllIDs.CustomerID) 
    OR NOT EXISTS (SELECT * FROM @TCustomerLocalization))
AND (EXISTS (SELECT * FROM @TCustomerGroup WHERE CustomerID = CteAllIDs.CustomerID) 
    OR NOT EXISTS (SELECT * FROM @TCustomerGroup))
AND (EXISTS (SELECT * FROM @TCustomerStore WHERE CustomerID = CteAllIDs.CustomerID) 
    OR NOT EXISTS (SELECT * FROM @TCustomerStore))
AND (EXISTS (SELECT * FROM @TCustomerSales WHERE CustomerID = CteAllIDs.CustomerID) 
    OR NOT EXISTS (SELECT * FROM @TCustomerSales))
AND (EXISTS (SELECT * FROM @TCustomerPayment WHERE CustomerID = CteAllIDs.CustomerID) 
    OR NOT EXISTS (SELECT * FROM @TCustomerPayment))