SQL:在1列上选择Distinct

时间:2017-05-10 10:24:54

标签: sql sql-server

我需要选择不同的值,但只需要1列,其他列需要显示最新记录,即:

customerID    Order Number    Order Date
00001         1000011         2017-01-01
00001         1000022         2017-01-10
00001         1000033         2017-02-01
00002         2000011         2016-12-01
00002         2000022         2017-01-01
00003         3000011         2017-03-01

我需要将其显示为:

 customerID   Order Number    Order Date
 00001        1000033         2017-02-01
 00002        2000022         2017-01-01
 00003        3000011         2017-03-01

在Postgresql中我会使用SELECT DISTINCT ON (customerID)然后按订单日期desc排序,但这在SQL Server中是不可能的。

我已尝试在订单日期使用Max功能,但如果应用如下所示,仍会在客户ID中返回重复项:

SELECT DISTINCT [CustomerID], [Order No], Max([Order Date])
FROM [T.ORDERS]
GROUP BY [CustomerID], [JOBNO]

5 个答案:

答案 0 :(得分:2)

您也可以使用JOIN

SELECT 
   A.[CustomerID], A.[Order No], A.[Order Date]
FROM [T.ORDERS] A INNER JOIN 
( 
  SELECT 
     [CustomerID], Max([Order Date])
  FROM [T.ORDERS]  
  GROUP BY A.[CustomerID], [JOBNO]
) B
ON A.[CustomerID]=B.[CustomerID] AND A.[Order Date]=B.[Order Date]

答案 1 :(得分:0)

您可以使用如下的row_number:

select * from
    (   Select *, RowN = Row_Number() over (partition by CustomerID order by [Order date] desc) from #yourtable ) a
   where a.RowN = 1

答案 2 :(得分:0)

您可能有此查询

SELECT DISTINCT customerID, MAX(OrderNumber), MAX(OrderDate) FROM table;

distinct比group by

更快

答案 3 :(得分:0)

你可以尝试使用ROW_NUMBER:

连接top的top 1
with Data as (
select '00001' customerID,         1000011 orderNumber,         cast('20170101'  as date)  orderdate union all
select '00001' customerID,         1000022 orderNumber,         '20170110' orderdate union all
select '00001' customerID,         1000033 orderNumber,         '20170201' orderdate union all
select '00002' customerID,         2000011 orderNumber,         '20161201' orderdate union all
select '00002' customerID,         2000022 orderNumber,         '20170101' orderdate union all
select '00003' customerID,         3000011 orderNumber,         '20170301' orderdate)
select top 1 with ties 
    CustomerID,
    OrderNumber,
    OrderDate 
from Data
order by 
    ROW_NUMBER() OVER (partition by CustomerID order by orderdate desc)

结果:

CustomerID  orderNumber orderdate
00001       1000033     2017-02-01
00002       2000022     2017-01-01
00003       3000011     2017-03-01

答案 4 :(得分:0)

如果你的桌子不大,你可以试试这样的东西:

SELECT [CustomerID], SUBSTRING(Dummy, 0, CHARINDEX('*', Dummy) - 1) AS [Order Date],
SUBSTRING(Dummy, CHARINDEX('*', Dummy), LEN(Dummy) - CHARINDEX('*', Dummy)) AS [Order No],
FROM (
      SELECT [CustomerID], 
      Max(CONVERT(varchar, [Order Date], 101) + '*' + CAST([Order No] as varchar)) AS Dummy
      FROM [T.ORDERS] GROUP BY [CustomerID]
      )

它正在做的是加入带有Order Date字符的Order No*字段(希望不会出现在任何列数据中的任何位置),然后在每个字段中选择其最大值组。在外部SELECT中,我们然后在*字符上拆分最大值以获取两个值。