tags:

views:

67

answers:

1

Hello,

sorry for the bad title, I don't know how to describe my problem.

I have the following table:

    |  ItemID  |    Date    |
    -------------------------
    |    1     |  01.01.10  |
    |    1     |  03.01.10  |
    |    1     |  05.01.10  |
    |    1     |  06.01.10  |
    |    1     |  10.01.10  |
    |    2     |  05.01.10  |
    |    2     |  10.01.10  |
    |    2     |  20.01.10  |

Now I want to GROUP BY ItemID and for the date I want to get the value, which excesses 60%. What I mean is, that for item 1 I've five rows, so each have a percentage of 20% and for item 2 I've three row, so each have a percentage of 33,33%. So for item 1 I need the 3rd and for item 2 the 2nd value, so that the result looks like that.

    |  ItemID  |    Date    |
    -------------------------
    |    1     |  06.01.10  |
    |    2     |  10.01.10  |

Is there a easy way so get this data? Maybe using OVER?

Thank you Torben

A: 
with NumItems as
( select itemID, count(*) as numOfItems from table group by itemID) 
),
rowNums as
( 
select itemID,Date, row_number() over (partition by ItemID order by date asc) as rowNum
from table
)
select itemID, min(Date) from
rowNums a inner join NumItems b on a.itemID = b.ItemID
where cast(b.rowNum as float) / cast(numOfItems as float) >= 0.6
group by itemID

that should do it although I am certain It can be writter with only one table scan. That should work nice though.

luckyluke
You can drop the NumItems cte and use a formula like having rowNum / max(rowNum) > 0.6 (with the casts of course) to avoid one table scan
luckyluke
Thank you, thats exactly what I need. I drop the NumItems and use COUNT(*) OVER (PARTITION BY ItemID) AS NumOfItems in RowNums.
Torben H.