在查询项目组中的第一个和最后一个项目时需要帮助

时间:2013-06-29 10:32:04

标签: sql sql-server-2008

我需要帮助才能获得此类输出:

Create table T1
(Id int identity primary key,
VoucherNo varchar(10),
TransNo varchar(10)
)

Insert into T1 values ('V100','Trns1'),('V101','Trns1'),('V102','Trns1'),('V103','Trns1'),('V104','Trns1'),('V106','Trns1')

结果输出:

TransNo FirsvoucherNo  LastVoucherNo Quantity
trans1    V100     V104  5
trans1   V106      V106   1

1 个答案:

答案 0 :(得分:1)

如果凭证号码的格式是固定的数字,可以通过简单的GROUP BY查询来解决:

SELECT
    TransNo,
    MIN(VoucherNo) as FirsvoucherNo,
    MAX(VoucherNo) as LastVoucherNo,
    COUNT(*) as Quantity
FROM T1
GROUP BY TransNo

Here is a demo on sqlfiddle.