简体   繁体   English

SQL Server 2014中的聚合

[英]Aggregation in SQL Server 2014

I have a data something like this: 我有这样的数据:

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'

I am trying to get a result like 我正在尝试获得类似的结果

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

Here sales is added for each customer from 1st Relation date to Last Relation date 在此,从第一个关联日期到最后一个关联日期为每个客户添加销售额

In a Till Last Relation Year COLUMN it contain highest year for each customer 在“最后一个联系年”列中,它包含每个客户的最高年份

I am not sure whether it is possible in SQL. 我不确定在SQL中是否可行。

Please share your suggestions. 请分享您的建议。

Thanks 谢谢

You could use: 您可以使用:

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

Rextester Demo Rextester演示

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

you can use below query - 您可以使用以下查询-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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