序列号为的SQL分组依据
这是我在SQL Server中的表:序列号为的SQL分组依据,sql,sql-server,tsql,Sql,Sql Server,Tsql,这是我在SQL Server中的表: Customer_Code Factor_Number Factor_Sum ------------------------------------------- 100 10 24500 100 15 12550 102 14 1000 103 18
Customer_Code Factor_Number Factor_Sum
-------------------------------------------
100 10 24500
100 15 12550
102 14 1000
103 18 65500
103 12 1000
我希望SQL Server中的输出不带任何临时表:
Customer_Code Factor_Count Factor_Sum Factor_Number
----------------------------------------------------------
100 2 37050 10,15
102 1 1000 14
103 2 66500 12,18
有人知道我怎么做吗?在CTE
中使用STRING\u AGG()
,然后再进行分组
drop table if exists #tmp
create table #tmp (customer_Code int, factor_number int, factor_sum int)
insert into #tmp
Values
(100,10,24500),
(100,15,12550),
(102,14,1000),
(103,18,65500),
(103,12,1000)
;with cte
as (
select customer_Code,STRING_AGG(factor_number,',') as factor_number
from #tmp
group by customer_Code)
select t.customer_Code,count(*) as Factor_Count, sum(factor_sum) as factor_sum, c.factor_number
from #tmp t
join cte c on t.customer_Code=c.customer_Code
group by t.customer_Code, c.factor_number
这看起来像是聚合:
select customer_code,
count(*) as factor_count,
sum(factor_sum) as factor_sum,
string_agg(factor_number, ',') within group (order by factor_number) as factor_numbers
from t
group by customer_code;
如果每个客户最多只有两行,那么您甚至不需要string\u agg()
:
似乎是一个非常简单的分组依据
,包含一个总和
、一个计数
和一个字符串_AGG
聚合。根据问题指南,请说明您尝试了什么,并告诉我们您(在本网站或其他地方)发现了什么,以及为什么它不能满足您的需求。
select customer_code,
count(*) as factor_count,
sum(factor_sum) as factor_sum,
concat_ws(',', min(factor_number), nullif(max(factor_number), min(factor_number)))
from t
group by customer_code;