我有一个表,其中有10个记录可用(使用批量插入插入记录)现在我想要选择一些带有行号和一些特定条件的记录。不管怎样我们得到记录的实际行号。
批量插入代码
BULK INSERT WorkDataLoad FROM 'D:\NPfiles\xyz.txt' with ( TABLOCK )
表 记录线
Record1
Record2
Record3
Record4
Record5
Record6
Record7
Record8
Record9
Record10
我试过这段代码,结果不太好
Select ROW_NUMBER() OVER(ORDER BY RecordLine DESC) AS RecordLine
from WorkDataLoad
where Recordline='Record1' or Recordline='Record3' or Recordline='Record5'
or Recordline='Record6' or Recordline='Record7' or Recordline='Record10'
结果
RowNumber Recordline
1 Record1
2 Record3
3 Record5
4 Record6
5 Record7
6 Record10
但我想要这样的记录
RowNumber Recordline
1 Record1
3 Record3
5 Record5
6 Record6
7 Record7
10 Record10
答案 0 :(得分:3)
使用row_number()
首先分配行号,然后仅选择所需的行:
with cteRows as
(
Select
RecordLine,
rn = ROW_NUMBER() OVER (ORDER BY RecordLine DESC)
from WorkDataLoad
)
select
rn, RecordLine
from cteRows
where
Recordline IN ('Record1', 'Record3', 'Record5', 'Record6', 'Record7', 'Record10')
如果您遇到了对“1
”和“10
”的排序问题,请使用类似的内容(假设每个RecordLine
以“Record
”开头):
with cteRows as
(
Select
RecordLine,
rn = ROW_NUMBER()
OVER (ORDER BY CAST(SUBSTRING(RecordLine, 7, LEN(RecordLine) - 6) as int) DESC)
from WorkDataLoad
)
select
rn, RecordLine
from cteRows
where
Recordline IN ('Record1', 'Record3', 'Record5', 'Record6', 'Record7', 'Record10')
答案 1 :(得分:0)
SELECT t.*
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY RecordLine DESC ) AS RowNo,
Recordline
FROM WorkDataLoad
) AS t
WHERE t.Recordline = 'Record1'
OR t.Recordline = 'Record3'
OR t.Recordline = 'Record5'
OR t.Recordline = 'Record6'
OR t.Recordline = 'Record7'
OR t.Recordline = 'Record10'
答案 2 :(得分:0)
如果我理解正确,你需要这个:
SELECT * FROM(
SELECT ROW_NUMBER () OVER (ORDER BY id) RowNumer,RecordLine FROM WorkDataLoad ) qry1
WHERE RecordLine IN ('Record1', 'Record3', 'Record5', 'Record6', 'Record7', 'Record10')
如果您的表格包含2列或更多列(id
,RecordLine
& ...)
答案 3 :(得分:-1)
select recordline,rn
Select
RecordLine,
rn = ROW_NUMBER() OVER (ORDER BY RecordLine DESC)
from WorkDataLoad) a
inner join WorkDataLoad b
on a.RecordLine=b.RecordLine
where
a.Recordline in ('Record1' ,'Record3' ,'Record5' ,'Record6' ,'Record7' ,'Record10')