我还有另外一个问题要问,但希望这个问题更加明确,并针对我需要帮助的问题。
示例数据:(下面包括Sample链接)
groupid custid cust_type cust_date data_total_1 data_total_2
CA123 ABC12345 SLE January, 01 2014 5 10
CA123 ABC12345 SLE February, 01 2014 2 5
CA123 ABC12345 SLE March, 01 2014 7 11
CA123 ABC12345 SLE April, 01 2014 7 4
FL444 BBB22222 SLE January, 01 2014 2 3
FL444 BBB22222 SLE March, 01 2014 7 21
FL444 BBB22222 SLE July, 01 2014 3 9
WA999 ZZZ99909 NSLE April, 01 2014 2 10
WA999 ZZZ99909 NSLE May, 01 2014 4 9对于每一个给定的石斑鱼,垫子,cust_type组合,我需要在给定的时间间隔(3个月)内获取评估记录。我需要计算记录的数量,并获取每个记录在“范围”内存在的最大data_total_x值。
我的预期输出类似于以下内容:
groupid custid cust_type cust_date custid_count max_data_total_1 max_data_total_2
CA123 ABC12345 SLE January, 01 2014 4 7 11
CA123 ABC12345 SLE February, 01 2014 3 7 11
CA123 ABC12345 SLE March, 01 2014 2 7 11
CA123 ABC12345 SLE April, 01 2014 1 7 4
FL444 BBB22222 SLE January, 01 2014 2 7 21
FL444 BBB22222 SLE March, 01 2014 1 7 21
FL444 BBB22222 SLE July, 01 2014 1 3 9
WA999 ZZZ99909 NSLE April, 01 2014 2 4 10
WA999 ZZZ99909 NSLE May, 01 2014 1 4 9包含示例数据的sample及其尝试:http://sqlfiddle.com/#!6/ba5a53/10/0
如能提供任何协助,将不胜感激。
发布于 2015-04-07 18:46:57
我认为这应该可以做到:
select
groupid,
custid,
cust_type,
f.custid_count,
f.max_data_total_1,
f.max_data_total_2
from records r
outer apply (
select
count(*) as custid_count,
max(data_total_1) as max_data_total_1,
max(data_total_2) as max_data_total_2
from
records r2
where
r.groupid = r2.groupid and
r.custid = r2.custid and
r.cust_type = r2.cust_type and
r2.cust_date <= dateadd(month, 3, r.cust_date) and
r2.cust_date >= r.cust_date
) fSQL:http://sqlfiddle.com/#!6/ba5a53/14
https://stackoverflow.com/questions/29498755
复制相似问题