访问SQL查询组

时间:2015-11-26 18:12:34

标签: sql tsql ms-access

我有一张TaxID,Price,DatePurchaced的表格 每个TaxId多次显示不同的价格和DatePurchaced 我想通过TaxId按Sum(Price)分组,并显示最后一个DatePurchaced 我还想要一个带有Count(TaxID)的列 我尝试了ome查询,但总是向我显示一条记录,其中包含最新的datePurchaced

1 个答案:

答案 0 :(得分:1)

declare @tbl as table (TaxID int, Price money, DatePurchaced datetime)

insert into @tbl (TaxID, Price, DatePurchaced) values (1, 10.5, '2015-03-05 10:25:23');
insert into @tbl (TaxID, Price, DatePurchaced) values (1, 13, '2015-03-09 10:25:23');
insert into @tbl (TaxID, Price, DatePurchaced) values (1, 7, '2015-03-20 10:25:23');
insert into @tbl (TaxID, Price, DatePurchaced) values (2, 10.5, '2015-07-05 10:25:23');
insert into @tbl (TaxID, Price, DatePurchaced) values (2, 8, '2015-07-08 10:25:23');


select  t.TaxId as TaxID, 
        count(t.TaxId) as Cnt,
        sum(t.Price) as TotalPrice,
        max(t.DatePurchaced) as LastPurchaseDate
from @tbl as t
group by t.TaxId