Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

more help with a where clause where I have to filter out states

$
0
0

I asked the same question yesterday and think I got most of the answer, but now I can't get it to work completly so I ask again with a more concrete example, scripts etc. (one of the posters also asked for that)

Original Question

Let us say we have a table with some orderstates, and I want the comment from the highest state per order, but I also want to include only some states.

Here is sample data

CREATE TABLE [dbo].[OrderState](
	[OrderId] [int] NOT NULL,
	[Status] [int] NOT NULL,
	[Comment] [varchar](50) NOT NULL,
 CONSTRAINT [PK_OrderState] PRIMARY KEY CLUSTERED 
(
	[OrderId] ASC,
	[Status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

INSERT INTO  OrderState VALUES (1,  1,  'received')
INSERT INTO  OrderState VALUES (1,  2,  'processed')
INSERT INTO  OrderState VALUES (1,  3,  'sent')
INSERT INTO  OrderState VALUES (2,  1,  'received')
INSERT INTO  OrderState VALUES (2,  2,  'processed')

GO

I am using some a 2005 database and some C# code, so my hope was that this view from yesterday solved something:

create view 
 LatestCommentView
 as
Select orderid, [status], comment, 
  Row_Number() Over(Partition By orderid Order By [status] Desc) As rn
From OrderState

And then I was hoping I could write something like this as the final SQL inside my code.

select * from LatestCommentView where [status] in (1,2) and rn=1

I would have liked 2 rows from this sql with the comment 'processed', but this does not work. Since I am suppressing status 3, then order 1 does not return anything with rn=1.

What am I missing. Or is it better to go some completly other way. I can't get any of the sql that begins with semicolons and starting with "With" to work.


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>