Click here to Skip to main content
15,890,845 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All.I want to select last record of price field of my table where my value of field is greater than zero. how can i do that?
my stored procedure is :
C#
SELECT id, name, price
FROM messages
WHERE id IN (
    SELECT MAX(id)
    FROM messages
   WHERE  price > 0
    GROUP BY name




the problem is that :
this code select max id that price is greater than zero not last id . means select id=2 and id=6
but in last id of group (frank) price is zero but this strored procedure select id=2 while I want stored procedure select only id =6
id name price
1 frank 1000
2 frank 500
3 frank 0
4 john 200
5 john 100
6 john 20

What I have tried:

how to select last id(where id >0) fod each group in sql server 2008
Posted
Updated 20-May-16 6:56am
Comments
CHill60 20-May-16 11:27am    
Then remove the GROUP BY name just to get the max id > 0
Rob Philpott 20-May-16 12:42pm    
CHill60 seems to have the answer. Maybe - I don't fully understand. Using the example rows about (1-6) - what output do you want?

The problem with "last" is that it's not precise: unless you specifically select a sort order via an ORDER BY statement (or similar) SQL is at liberty to return rows in any order it finds convenient. Normally, that works out as "first in, first out", so a vanilla SELECT such as
SQL
SELECT * FROM MyTable
will return rows in the order that they were INSERTED.
But...it's not necessarily so! In order to be certain of your "last" row, you need to tell SQL explicitly what to order by.
So...add a "InsertDate" or "TimeStamp" column, and set it when you INSERT (the easiest way is to provide a DATETIME column and set it's DEFAULT to GETDATE() - then SQL will supply it for you without your external code having to change).
Then you have a column that can work with the GROUP BY clause to specify the "last" row in each group.
 
Share this answer
 
If I've understood your question properly, something like this should work:
SQL
WITH cteMessages As
(
    SELECT
        id,
        name,
        price,
        ROW_NUMBER() OVER (PARTITION BY name ORDER BY id DESC) As RN
    FROM
        messages
)
SELECT 
    id, 
    name, 
    price
FROM
    cteMessages
WHERE
    RN = 1
And
    price > 0
;

That will find the row with the highest id for each name, and then only return those rows where the price is greater than zero.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900