Sql select min return value from another column in the same row with grouping
I need an OrderType for min (Date) for each name. So, I want this:
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
to get this back:
Name Date OrderType
Alex 1/1/2014 Direct
Cindy 6/4/2014 Distributor
John 2/14/2014 Distributor
+3
source to share
4 answers
I think you need to select the min date per person and then join the original table to get the type for that row.
Assuming your table is called a tab and each person only had one order per date (otherwise the question is not possible) then something like:
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
Sorry that I am working mainly with mysql and Oracle, not tsql, so this is the general sql syntax.
+1
source to share
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
0
source to share