仅在一列上有所区别

时间:2017-05-11 19:02:04

标签: sql distinct

我想只使用SQL管理工作室获取不同的帐户

SELECT DISTINCT [Account]
  ,[Opportunity Name]
  ,[LeadContact Email]
  ,[LeadContact Name]
  ,[LeadContact Status]
FROM NAME
 WHERE [Account Addr Country] LIKE '%US%'
 AND [LeadContact Name] NOT LIKE '%Test%'
ORDER BY [Account]

2 个答案:

答案 0 :(得分:0)

在SQL Server中,您可以使用ROW_NUMBER()

SELECT Account, [Opportunity Name], [LeadContact Email],
      [LeadContact Name], [LeadContact Status]
FROM (SELECT n.*,
             ROW_NUMBER() OVER (PARTITION BY Account ORDER BY Account) as seqnum
      FROM NAME n
      WHERE [Account Addr Country] LIKE '%US%' AND
            [LeadContact Name] NOT LIKE '%Test%'
     ) n
WHERE seqnum = 1;

这会选择一个不确定的行。如果您想要特定行(例如最早或最新或最大或最小),您可以调整ORDER BY子句。

答案 1 :(得分:-2)

在我看来,最简单的方法是执行以下请求:

    SELECT 
     [Account]
     ,[Opportunity Name]
     ,[LeadContact Email]
     ,[LeadContact Name]
     ,[LeadContact Status]
    FROM NAME n inner join (
      SELECT distinct [Account] FROM NAME 
      WHERE [Account Addr Country] LIKE '%US%'
      AND [LeadContact Name] NOT LIKE '%Test%' ORDER BY [Account]) n2
    on n.Account = n2.account

第一个内部请求检索所有不同的帐户,第二个请求检索补充信息