如何返回多列,但删除1列

时间:2015-07-09 02:28:15

标签: sql sql-server sql-server-2008 tsql distinct

我尝试编写查询以返回所有列,并通过显示特定列中的DISTINCT记录进行过滤。

现在这是我的查询,这需要我去" Group By" select语句中的所有内容。我显然不想这样做。:

SELECT     lVisitID, sFirstName, sLastName, sAddress1, sStoreNumber
FROM        Customers
WHERE     (dtServiceDate < '5/1/15') AND (sStoreNumber = '123') 
GROUP BY sAddress1

我也尝试过以下内容,但是会返回重复内容:

    SELECT     lVisitID, MAX(sAddress1)
    FROM        Customers
    WHERE     (dtServiceDate < '5/1/15') AND (sStoreNumber = '123') 
    GROUP BY sAddress1, lvisitID

这是我的数据:

lVisitID     sFirstName   sLastName     sAddress1     sStoreNumber
  1             Bob          Jones         14 Place     123
  2             Jim          Bibby         12 Place     123
  3             John         Smith         12 Place     123
  4             Jen         Jones          22 Place     193
  6             Kim         Smith          15 Place     123

这里的想法是仅返回不同的地址和商店编号。当我尝试上述内容时,我需要:

  1             Bob          Jones         14 Place     123
  2             Jim          Bibby         12 Place     123
  6             Kim         Smith          15 Place     123

2 个答案:

答案 0 :(得分:3)

如果您只想要访问最近一次的地址,请使用row_number()

select c.*
from (select c.*,
             row_number() over (partition by address order by lVisitId desc) as seqnum
      from customers c
     ) c
where seqnum = 1;

答案 1 :(得分:1)

我在Postgres SQL上试过这个。

SELECT     Distinct on (sAddress1) *
FROM        Customers
WHERE     (dtServiceDate < '5/1/15') AND (sStoreNumber = '123')