1

連続した行番号を取得しようとしていますが、何をしようとしてもうまくいきません。これが私のクエリです

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
4

1 に答える 1

5

あなたのカウントは、dbo.mac_actlocmapの集計されていない、フィルター処理されていない行をカウントしています。ただし、集計とフィルターを使用したサブクエリと比較しています。

この複雑さでは、一時テーブルを使用します。SQL Server 2000 で ROW_NUMBER をエミュレートするために必要な三角結合に対して、まったく同じクエリを 2 回実行するよりも簡単です。

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
于 2011-04-17T20:17:31.497 に答える