Hi all,
I have been stuck on a particular use of the DENSE_RANK() function.
I am trying to partition by a column but order by another column, but when I try to partition by a column SQL is ordering by the column i specified in the partition - very annoying! So here is my dataset:
WITH dataSet AS ( SELECT 'Apple' AS Fruit, CAST('20130101' AS DATE) AS EatenDate
UNION ALL
SELECT 'Apple', '20130102'
UNION ALL
SELECT 'Pear', '20130102'
UNION ALL
SELECT 'Pear', '20130103'
UNION ALL
SELECT 'Apple', '20130104'
UNION ALL
SELECT 'Apple', '20130105'
UNION ALL
SELECT 'Pear', '20130106'
UNION ALL
SELECT 'Apple', '20130107')
SELECT *,DENSE_RANK() OVER(PARTITION BY FRUIT ORDER BY EATENDATE) AS Ranking
FROM DataSet
Here are the results
Fruit EatenDate Ranking
Apple 2013-01-01 1
Apple 2013-01-02 2
Apple 2013-01-04 3
Apple 2013-01-05 4
Apple 2013-01-07 5
Pear 2013-01-02 1
Pear 2013-01-03 2
Pear 2013-01-06 3
but what i'm after is:
Fruit EatenDate Ranking
Apple 2013-01-01 1
Apple 2013-01-02 1
Pear 2013-01-02 2
Pear 2013-01-03 2
Apple 2013-01-04 3
Apple 2013-01-05 3
Pear 2013-01-06 4
Apple 2013-01-07 5
My workaround is (I know, its very long winded):
DECLARE @FruitPrev varchar(10) = 'Apple', @Row_Number_Inc AS INT = 1;
DECLARE @TableVar TABLE( Fruit VARCHAR(10) null, EatenDate DATE null, Ranking INT null)
DECLARE @vFruit VARCHAR(10), @vEatenDate DATE
DECLARE Fruity CURSOR FOR
SELECT 'Apple' AS Fruit, CAST('20130101' AS DATE) AS EatenDate UNION ALL
SELECT 'Apple', '20130102' UNION ALL
SELECT 'Pear', '20130102' UNION ALL
SELECT 'Pear', '20130103' UNION ALL
SELECT 'Apple', '20130104' UNION ALL
SELECT 'Apple', '20130105' UNION ALL
SELECT 'Pear', '20130106' UNION ALL
SELECT 'Apple', '20130107';
OPEN Fruity
FETCH NEXT FROM Fruity INTO @vFruit, @vEatenDate
WHILE (@@FETCH_STATUS <> -1)
BEGIN
IF @vFruit = @FruitPrev
BEGIN
INSERT INTO @TableVar VALUES(@vFruit, @vEatenDate, @Row_Number_Inc);
SET @FruitPrev = @vFruit;
END
ELSE
BEGIN
SET @Row_Number_Inc += 1;
INSERT INTO @TableVar VALUES(@vFruit, @vEatenDate, @Row_Number_Inc);
SET @FruitPrev = @vFruit;
END
FETCH NEXT FROM Fruity INTO @vFruit, @vEatenDateENDCLOSE Fruity
DEALLOCATE Fruity
SELECT * FROM @TableVar
Is there an easier way to do this using one of the ranking functions?
Your help would be appreciated especially if it can be applied to my example above.
Shaheen Karatela