2017-08-30 77 views
1

我有一個數據是這樣的:聚集在SQL Server 2014

declare @table table 
(
    CUSTNO varchar(35), 
    RELATIONNO int, 
    Sales numeric(5,2), 
    RelationDate dateTIME 
) 

insert into @table 

select 'B1024818', 120, 189.26, '2013-10-27' union all 
select 'B1024818', 120, 131.76, '2016-10-28' union all 
select 'C0002227', 124, 877.16, '2012-08-26' union all 
select 'C0002227', 124, 802.65, '2015-06-15' 

我想獲得像

CUSTNO  RELATIONNO  Sales Till Last Relation Year 
---------------------------------------------------------- 
B1024818  120  321.02   2016 
C0002227  124  1679.81   2015 

這裏的銷售是從1日關係日至每個客戶加入結果Last Relationship date

直到最後一個關聯年COLUMN它包含每個客戶的最高年份

我不確定在SQL中是否有可能。

請分享您的建議。

感謝

回答

1
SELECT custno, RELATIONNO, sum(Sales), MAX(year(RelationDate)) 
FROM @table 
GROUP BY custno, RELATIONNO 
2

你可以使用:

SELECT CUSTNO, RELATIONNO, SUM(Sales) AS Sales, MAX(YEAR(RelationDate)) 
FROM @table 
GROUP BY CUSTNO, RELATIONNO; 

Rextester Demo

1

您可以使用下面的查詢 -

select CUSTNO ,RELATIONNO ,SUM(Sales) as Sales , max(Year(RelationDate)) [Till Last Relation Year] 
from @table 
group by CUSTNO ,RELATIONNO