SQL选择最小值,返回同一行中不同列的值并进行分组

5

我想要每个名称的最小日期的OrderType。

Name    Date        OrderType
Alex    1/1/2014    Direct
Alex    9/15/2014   Distributor
Cindy   6/4/2014    Distributor
John    5/8/2014    Direct
John    2/14/2014   Distributor

返回这个:

Name    Date        OrderType
Alex    1/1/2014    Direct
Cindy   6/4/2014    Distributor
John    2/14/2014   Distributor

感谢@JChao的格式编辑! - Scott Leas
4个回答

13

我们可以针对每个[Name]按日期获取行号,并选择最早的日期记录。

SELECT [T].* 
FROM (  
    SELECT [Name]
         , [DATE]
         , [OrderType]
         , ROW_NUMBER() OVER (PARTITION BY [Name] ORDER BY [Date]) AS [seq]
    FROM [TableA]
) AS [T]
WHERE [T].[seq] = 1

1
惊呆了。完美的解决方案!谢谢你。 - Scott Leas

1
我认为您需要选择每个人的最小日期,然后将其与原始表格连接以获取该行的类型。假设您的表格名为tab,并且每个人每天只有一个订单(否则问题是不可能的),那么可以使用以下代码:
Select t.name, t.date, t.ordertype
From tab t,
     ( select min (i.date) date, i.name from tab i group by i.name) t2
Where t.date = t2.date
  And t.name = t2.name

抱歉,我主要使用mysql和Oracle而不是tsql,因此这是通用的SQL语法。

0
CREATE TABLE #tmp
( Name VARCHAR(50), orderdate DATE, OrderType VARCHAR(50) )
INSERT #tmp ( Name, orderdate, OrderType )
VALUES  ( 'Alex', '01/01/2014','Direct')
INSERT #tmp
VALUES  ( 'Alex', '9/15/2014','Distributor')
INSERT #tmp
VALUES  ( 'Cindy', '6/4/2014','Distributor')
INSERT #tmp
VALUES  ( 'John', '5/8/2014','Direct')
INSERT #tmp
VALUES  ( 'John', '2/14/2014','Distributor')


; WITH CTE_RESULT AS
(
    SELECT ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY ORDERDATE ASC) ROW_NO , Name, orderdate, OrderType
    FROM #tmp
)

SELECT  * FROM CTE_RESULT T WHERE T.ROW_NO=1

-2

试一下

select 
a.name, 
MIN(a.date)as date, 


from dbname a i
inner join (select name, min(date), ordertype from dbname) b on b.name=a.name and a.date=b.date

group by a.name, b.ordertype 

1
我没有给这个点踩,但是你的查询会返回所有5行,因为它是按名称和订单类型分组的。 - SQLChao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接