日期:2014-05-17 浏览次数:20670 次
Card_ID nvarchar(20) 省份证号
Person_Type int 人员类型 (1在职 2 退休)
Fee_Date DateTime 消费日期
Fee_Amount Decimal 消费金额
card_id person_Type Fee_Date Fee_Amount
1001 1 2013-1-1 20
1002 1 2013-1-2 20
1003 2 2013-1-3 20
1004 2 2013-1-1 20
1001 2 2013-3-1 20
1001 1 2013-1-1 20
1004 1 2013-2-1 20
person_Type 次数 Fee_Amount
1 6 100
2 1 20
-- data
if object_id('tempdb.dbo.#') is not null drop table #
create table #(card_id int, person_Type int, Fee_Date date, Fee_Amount int)
insert into #
select 1001, 1, '2013-1-1', 20 union all
select 1002, 1, '2013-1-2', 20 union all
select 1003, 2, '2013-1-3', 20 union all
select 1004, 2, '2013-1-1', 20 union all
select 1001, 2, '2013-3-1', 20 union all
select 1001, 1, '2013-1-1', 20 union all
select 1004, 1, '2013-2-1', 20
-- query
;with data as
(
--select id=row_number()over(order by Fee_Date), * from # -- 按Fee_Date衡量1001最后1次的person_Type是2
select id=row_number()over(order by getdate()), * from #
), a as
(
select * from data t where not exists (select 1 from data where card_id=t.card_id and id>t.id)
)
select a.person_type, count(1)cn, sum(b.Fee_Amount)Fee_Amount from a, # b where a.card_id=b.card_id group by a.person