sql select min,从同一行的不同列返回值并进行分组

时间:2014-09-18 20:50:14

标签: sql sql-server tsql

我希望OrderType为每个Name的min(Date)。 所以,我想要这个:

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

4 个答案:

答案 0 :(得分: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 :(得分: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语法。

答案 2 :(得分: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

答案 3 :(得分:-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