This one is hard to explain. I’m trying to do a Row_Number() Over(Order by PickedDate) in my select insert into a new table.
This works fine for producing 1,2,3,4,5,6,7, but that’s not what i’m looking to do. I’m Looking to generate the row back at the number one for each grouping of fruit.
For example I have the following table structure i’m trying to insert into; ItemOrder int, FruitType nvarchar(100),DatePicked datetime,
with the following data
FruitType|DatePicked Apple|10/1/2012 Apple|10/3/2012 Apple|10/2/2012 Plum|9/13/2011 Plum|9/14/2011 Plum|9/15/2011 Cherry|12/2/2012 Cherry|12/4/2012
I’m trying to get the following result
FruitType|DatePicked|ItemOrder Apple|10/1/2012|1 Apple|10/3/2012|3 Apple|10/2/2012|2 Plum|9/13/2011|1 Plum|9/14/2011|2 Plum|9/15/2011|3 Cherry|12/2/2012|1 Cherry|12/4/2012|2
to help everybody out
CREATE TABLE #FruitStandPicked
(
FruitType NVARCHAR (100),
DatePicked DATETIME
);
INSERT INTO #FruitStandPicked (FruitType, DatePicked)
VALUES ('Apple', '10/1/2012'),
('Apple', '10/3/2012'),
('Apple', '10/2/2012'),
('Plum', '9/13/2011'),
('Plum', '9/14/2011'),
('Plum', '9/15/2011'),
('Cherry', '12/2/2012'),
('Cherry', '12/4/2012');
CREATE TABLE #FruitStandTable
(
Itemorder INT,
FruitType NVARCHAR (100),
DatePicked DATETIME
);
--this needs the tweak
INSERT INTO #FruitStandTable (ItemOrder, FruitType, DatePicked)
SELECT row_number () OVER (ORDER BY fruittype, datepicked),
FruitType,
DatePicked
FROM #FruitStandPicked;
SELECT * FROM #FruitStandTable;
DROP TABLE #FruitStandTable;
DROP TABLE #FruitStandPicked;
Again that works to the extent of making the order, but I need the order by grouping also.
Thanks in advance!
You can still use
ROW_NUMBERwithPARTITIONclause.Try this: