Question

i'm stuck with a query and i don't want to use a while loop or another nasty method to do this.

Here's the situation:

I've got a query that gets some data, and i need to calculate a column based on 2 other columns.

My results are as follow: Type | Customer | Cycle | Amount | Expiration | Row_Number (Partition By Customer, Cycle)

So, my row_number column needs to "group" customers and cycles, here's a Fiddle to better understand it

Here's an example: My actual results

As you can see, iteration column is correctly applied as far as i know what row_number does. But i need to do this: How i need my data

Is there a way to do this with Row_Number ?

or should i need store the data in a temp table, loop through it and update this ITERATION column?

Maybe a CTE? Any help on this will be highly appreciated. Thanks!

Was it helpful?

Solution 2

You could use DENSE_RANK function instead of ROW_NUMBER.

DECLARE @MyTable TABLE
(
    Customer NVARCHAR(100) NOT NULL,
    [Cycle] SMALLINT NOT NULL
);
INSERT @MyTable VALUES ('C1', 2010);
INSERT @MyTable VALUES ('C1', 2010);
INSERT @MyTable VALUES ('C1', 2011);
INSERT @MyTable VALUES ('C1', 2012);
INSERT @MyTable VALUES ('C1', 2012);
INSERT @MyTable VALUES ('C1', 2012);
INSERT @MyTable VALUES ('C2', 2010);
INSERT @MyTable VALUES ('C2', 2010);

SELECT  t.Customer, t.[Cycle], 
        DENSE_RANK() OVER(PARTITION BY t.Customer ORDER BY t.[Cycle]) AS Rnk
FROM    @MyTable t
ORDER BY Customer, [Cycle];

Results:

Customer Cycle  Rnk
-------- ------ ---
C1       2010   1
C1       2010   1
C1       2011   2
C1       2012   3
C1       2012   3
C1       2012   3
C2       2010   1
C2       2010   1

SQL Fiddle

OTHER TIPS

just run this as new query, replace what you need in your query...

WITH T(StyleID, ID)
     AS (SELECT 1,1 UNION ALL
         SELECT 1,1 UNION ALL
         SELECT 1,1 UNION ALL
         SELECT 1,2)
SELECT *,
      RANK() OVER(PARTITION BY StyleID ORDER BY ID)       AS 'RANK',
      ROW_NUMBER() OVER(PARTITION BY StyleID ORDER BY ID) AS 'ROW_NUMBER',
       DENSE_RANK() OVER(PARTITION BY StyleID ORDER BY ID) AS 'DENSE_RANK'
FROM   T  

regards,
Valentin

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top