tags:

views:

31

answers:

2

Hi,

Assume there were 100 records in tableA and tableA contained a column named 'price'.

How do I select the first-n record if where sum of price > a certain amount (e.g. 1000) without using cursor?

thanks

A: 

select price from tableA where price > 1000 limit n;

n - no. of records you want in result set

-- Cheers

Koteswara sarma
I think you guys all misunderstood the question sorry.. Basically I need to sum the price column and if the same has reached the limit then take the records. So if the price in record #1 + the price in record #2 + the price in record #3 has reached the limit then take those three records otherwise keep on looping thru the records until reaching the limit
LIMIT is not TSQL...
astander
+1  A: 

Top N implies some kind of order, which you did not supply, so I assumed any random order.

You can change this on the OVER clause of the ROW_NUMBER().

Try something like

DECLARE @Table TABLE(
        Price FLOAT
)

INSERT INTO @Table SELECT 1
INSERT INTO @Table SELECT 11
INSERT INTO @Table SELECT 12
INSERT INTO @Table SELECT 15
INSERT INTO @Table SELECT 10
INSERT INTO @Table SELECT 65
INSERT INTO @Table SELECT 100

DECLARE @TotalPrice FLOAT
SELECT  @TotalPrice = 100

;WITH Vals AS (
        SELECT  *,
                ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) RNR
        FROM    @Table
)
, Totals AS (
        SELECT  v.RNR,
                SUM(vP.Price) TotalPrice
        FROM    Vals v LEFT JOIN
                Vals vP ON  v.RNR >= vP.RNR
        GROUP BY    v.RNR
)
, LimitValue AS (
        SELECT  TOP 1 
                RNR
        FROM    Totals
        WHERE   TotalPrice >= @TotalPrice
        ORDER BY    RNR
)
SELECT  *
FROM    Vals 
WHERE   RNR <= (
                    SELECT  RNR
                    FROM    LimitValue
                )
astander
performance wise, is it better than cursor?
typically, set based queries are faster than cursors, but you should test and benchmark this.
astander
yes.. have tested for 41K records with average selecting 12K records, the query run for 10 minutes.. is there away to speed it up?
Do you have any indexes on the table?
astander