sql distinct从多个select中选择

时间:2015-02-18 13:52:19

标签: sql database sql-server-2008 tsql

加入以下三个select并获取非重复的contact.id的最佳方法是什么?

有什么想法吗?

 SELECT distinct ct.id
  FROM [Customer].[dbo].[Contact] ct 
  left join [Customer].[dbo].[HN_Customer_ids] hnids 
       on ct.id = hnids.contact_id 
  left join [CustomerTransactions].[dbo].[Transaction_Header] trh 
       on trh.Customer_ID = hnids.HN_customer_id
 where trh.actual_transaction_date > '20120218'

结果:231360

  SELECT count(distinct(contact_id))
  FROM [Customer].[dbo].[Restaurant_Attendance]
  where ( created > '2012-02-18 00:00:00.000' or modified > '2012-02-18 00:00:00.000') 
    AND 

结果:1​​67128

 SELECT distinct aaa.id
  FROM [Customer].[dbo].[Contact] aaa 
  left join [Customer].[dbo].[Wifinity_Devices] bbb 
       on aaa.wifinity_uniqueID = bbb.[CustomerUniqueID]
  and startconnection > '2012-02-17'

结果:77290

3 个答案:

答案 0 :(得分:1)

使用union

SELECT ct.id
  FROM [Customer].[dbo].[Contact] ct 
  left join [Customer].[dbo].[HN_Customer_ids] hnids on ct.id = hnids.contact_id 
  left join [CustomerTransactions].[dbo].[Transaction_Header] trh on trh.Customer_ID = hnids.HN_customer_id
  where trh.actual_transaction_date > '20120218'
union 
 SELECT  contact_id 
  FROM [Customer].[dbo].[Restaurant_Attendance]
  where ( created > '2012-02-18 00:00:00.000' or modified > '2012-02-18 00:00:00.000')
union 
 SELECT aaa.id
  FROM [Customer].[dbo].[Contact] aaa left join [Customer].[dbo].[Wifinity_Devices] bbb on aaa.wifinity_uniqueID = bbb.[CustomerUniqueID]
  and startconnection > '2012-02-17'

答案 1 :(得分:1)

使用union。所以:

SELECT ct.id
FROM [Customer].[dbo].[Contact] ct join
     [Customer].[dbo].[HN_Customer_ids] hnids
     on ct.id = hnids.contact_id join
     [CustomerTransactions].[dbo].[Transaction_Header] trh
     on trh.Customer_ID = hnids.HN_customer_id
WHERE trh.actual_transaction_date > '20120218'
UNION
SELECT contact_id
FROM [Customer].[dbo].[Restaurant_Attendance]
WHERE (created > '2012-02-18 00:00:00.000' or
       modified > '2012-02-18 00:00:00.000')
UNION
SELECT aaa.id
FROM [Customer].[dbo].[Contact] aaa ;

第一次和第三次查询中不需要left join。首先,where撤消left join无论如何。第三,您从第一个表中选择了id,而left join没有过滤。

答案 2 :(得分:0)

假设所有查询都针对同一个Contact表运行,则使用left outer join会有效地导致第三个查询返回 all 联系人。除非第二个查询可以添加Contact表中未找到的contact_ids,否则最终结果等同于:

select /* distinct, if not a pk */ contact_id from Customer.dbo.Contact

您的行计数表明这些实际上可能是来自不同数据库的表。是这样的吗?