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

时间:2015-08-28 02:13:22

标签: sql-server vb.net-2010

我正在尝试获取特定日期的第一张收据号码和最后一张收据号码。有没有办法在一个声明中得到它?我可以使用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)
.......

我可以在一个陈述中获得摊位值并将其放在变量中,以便我可以将它分别放在两个标签上吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

试试这个

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 

答案 1 :(得分:0)

另一种方式就是......

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