Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Using partition for row number

Author  Topic 

chris_cs
Posting Yak Master

223 Posts

Posted - 2010-06-15 : 10:12:01
Hey,

I'm using the following code:


declare @startDate datetime
declare @endDate datetime
set @startDate = '2009-01-01 00:00:00.000'
set @endDate = '2009-02-01 00:00:00.000'

select
n.name,
n.namecode,
dh.openitemno,
convert(varchar, dh.transdate, 103) as t_date,
dh.localvalue,
isnull(dh.foreigntranvalue, 0) as foreigntranvalue,
c.irn,
cn.referenceno, row_number() over (partition by n.namecode order by n.namecode asc) as row
from debtorhistory dh
inner join name n on n.nameno = dh.acctdebtorno
inner join (
select distinct(caseid), reftransno
from workhistory
) as ci
on ci.reftransno = dh.itemtransno
inner join cases c on c.caseid = ci.caseid
inner join casename cn on cn.caseid = c.caseid and cn.nametype = 'D' and cn.sequence = 0
where dh.transtype in (510, 511, 512, 515, 516)
and dh.transdate between @startDate and @endDate
and row = 1
group by dh.openitemno, n.name, n.namecode, dh.transdate, dh.localvalue, dh.foreigntranvalue, dh.referencetext, c.irn, cn.referenceno


The query is working as I'd like but I only want to return the rows with a value of 1. I tried referring to the column 'row' I created but it isn't working.

I'm sure this is simple but I can't get it to work.

Any ideas?

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2010-06-15 : 10:18:25
Put the whole statement in parenthesis, give it an alias and then select from this derived table.

select *
from (here comes your select) as dt
where row=1


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

chris_cs
Posting Yak Master

223 Posts

Posted - 2010-06-15 : 10:22:56
Doh!

I should have thought of that.

Thanks!
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2010-06-15 : 10:31:06
welcome


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page
   

- Advertisement -