SQL Server 2000行编号

时间:2011-04-17 20:10:40

标签: sql sql-server-2000 row-number

我正在尝试获取顺序行编号,但无论我尝试什么都不起作用。这是我的查询

select
    l.seq, l.mn_no as mn_no, l.sb_no as sb_no,
    l.dp_no as dp_no,
    sum(costprice) as amt
from 
    dbo.mac_pur_tempdetail d
inner join 
    dbo.mac_pur_tempheader h on d.header_id = h.header_id
                              and h.ref = 'SAH1FIHC'
inner join 
    dbo.mac_actlocmap l on l.loc_main = d.loc_id
                         and l.description = 'PUR'
group by  
    l.seq, l.mn_no, l.sb_no, l.dp_no

以下是该查询的结果

1   4110        30          0000        17.5000
4   4110        20          0000        3.6000
6   4110        40          0000        6.0000
7   4110        10          0000        1.8000
14  4110        25          0000        3.6000
15  4110        50          0000        1.8000

我试过

select
    (select count(seq)  
     from dbo.mac_actlocmap s
     where s.seq <= a.seq and a.mn_no = s.mn_no) as new_seq,
    * 
from 
    (select
         l.seq, l.mn_no as mn_no,
         l.sb_no as sb_no, l.dp_no as dp_no,
         sum(costprice) as amt
     from 
         dbo.mac_pur_tempdetail d
     inner join 
         dbo.mac_pur_tempheader h on d.header_id = h.header_id
                                  and h.ref = 'SAH1FIHC'
     inner join 
         dbo.mac_actlocmap l on l.loc_main = d.loc_id
                              and l.description = 'PUR'
     group by  
         l.seq, l.mn_no, l.sb_no, l.dp_no) a

但结果是

1   1   4110        30          0000        17.5000
2   4   4110        20          0000        3.6000
3   6   4110        40          0000        6.0000
4   7   4110        10          0000        1.8000
7   14  4110        25          0000        3.6000
8   15  4110        50          0000        1.8000

1 个答案:

答案 0 :(得分:5)

您的计数是在dbo.mac_actlocmap中计算 unaggregated 未过滤的行。但是您要与子查询进行比较聚合和过滤。

由于这种复杂性,请使用临时表。这比在SQL Server 2000上模拟ROW_NUMBER所需的三角形连接两次完全相同的查询更容易

select
l.seq,
l.mn_no as mn_no,
l.sb_no as sb_no,
l.dp_no as dp_no,
sum(costprice) as amt

INTO #foo

from dbo.mac_pur_tempdetail d
inner join dbo.mac_pur_tempheader h
on d.header_id = h.header_id
and h.ref = 'SAH1FIHC'
inner join dbo.mac_actlocmap l
on l.loc_main = d.loc_id
and l.description = 'PUR'
group by  l.seq,l.mn_no,l.sb_no,l.dp_no

select
(select count(seq) from #foo s
where s.seq <= a.seq and a.mn_no = s.mn_no) as new_seq,
* from #foo a