我可以在 Sql 服务器中的单个查询中获取第一个和最后一个事务吗?

Can I get the First and Last Transaction in a single query in Sql Server?

我正在尝试获取特定日期的第一个收据编号和最后一个收据编号。有没有办法在一个声明中得到它?我可以使用 2 个语句来获取它:

cnn.Open()
query = "select top 1(invoice) from invoice_tbl where transaction_date = @transaction_date order by invoice Desc"
cmd = new sqlCommand(query,cnn)
.......

cnn.Open()
query = "select top 1(invoice) from invoice_tbl where transaction_date = @transaction_date order by invoice Asc"
cmd = new sqlCommand(query,cnn)
.......

我能否在单个语句中获取展位值并将其放入变量中,以便我可以将其分别放置在两个标签上?

谢谢!

试试这个

select 
(select top 1(invoice) 
from invoice_tbl 
where transaction_date = @transaction_date order by invoice Desc) as last_inv ,
(select top 1(invoice) 
from invoice_tbl 
where transaction_date = @transaction_date order by invoice Asc) as First_inv 

另一种方式是……

SELECT invoice
FROM (
select   invoice
        ,ROW_NUMBER() OVER (order by invoice DESC) Last_Invc
        ,ROW_NUMBER() OVER (order by invoice ASC ) First_Invc
from invoice_tbl 
where transaction_date = @transaction_date 
) t
WHERE Last_Invc = 1
   OR First_Invc = 1