2011-04-17 88 views
1

我試圖獲得一個連續的行編號,但無論我嘗試不工作。這裏是我的查詢SQL Server 2000行編號

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 
+0

您是否嘗試過使用ROW_NUMBER()?我不確定它是否適用於SQL Server 2000 - http://msdn.microsoft.com/zh-cn/library/ms186734.aspx – 2011-04-17 20:14:48

+1

您的計數正在計算dbo.mac_actlocmap中的* unaggregated *和* unfiltered *行。但是你正在比較一個帶有聚合和過濾器的子查詢*。 – gbn 2011-04-17 20:15:53

+1

@SeanA:ROW_NUMBER()在SQL Server ** 2005中引入** ** – 2011-04-17 20:21:33

回答

5

你計數計數未聚集未過濾 dbo.mac_actlocmap中的行。但是,您正在比較子查詢聚合和過濾器。

由於這種複雜性,請使用臨時表。這隻比在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 
+0

我試圖避免臨時表......只是認爲我在查詢中做錯了什麼......猜測我別無選擇。謝謝。 – 2011-04-17 20:22:33