简体   繁体   中英

Access SQL query group by

我有一个包含TaxID,Price,DatePurchaced的表,每个TaxId多次显示不同的Price和DatePurchaced,我想按Sum(Price)按TaxId分组,并显示最后一个DatePurchaced,我也想用Count(TaxID)列尝试一下查询,但总是向我显示一条记录,记录最新的日期

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM