2014-09-18 91 views
3

我希望每个Name的min(Date)的OrderType。 所以,我想这一点:sql select min,从同一行中的不同列返回值与分组

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 
+0

感谢格式化编辑@JChao! – 2014-09-18 20:58:19

回答

10

我们可以根据日期为每个[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

头脑风暴。完美解决方案谢谢你 – 2014-09-18 21:08:51

-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行,因为它是按名称和ordertype分组的。 – SQLChao 2014-09-18 21:03:43

1

我想你需要选择每人分钟时间再加入回原来的表来获得该行的类型。

假设你的表称为标签,每个人只有每个日期的顺序(否则,问题是不可能的),那么这样的:

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 
相关问题