2016-05-31 86 views
0

如何根据字符串的一部分对数据进行分组。如何根据字符串的一部分进行分组

示例数据:

StringA ValueA ValueB 
47353-1 123 1440 
47353-2 235 9472 
47353-3 44  439 
47355-1 21  482 

结果想:

StringA Count SumA SumB 
47353  3 402 11351 
47355  1 21 482 

如果我使用组由StringA,它出错。

回答

0

使用带有CHARINDEX的左侧给出此数据(用于测试的数据),这将允许在必要时使用不同长度的字段。

测试数据;

CREATE TABLE #TableName (StringA varchar(10), ValueA int, ValueB int) 
INSERT INTO #TableName (StringA, ValueA, ValueB) 
VALUES 
('47353-1',123,1440) 
,('47353-2',235,9472) 
,('47353-3',44,439) 
,('47355-1',21,482) 

实际查询;

SELECT 
    LEFT(StringA,CHARINDEX('-',StringA,0)-1) StringA 
    ,COUNT(StringA) Count 
    ,SUM(ValueA) SumA 
    ,SUM(ValueB) SumB 
FROM 
    #TableName 
GROUP BY 
    LEFT(StringA,CHARINDEX('-',StringA,0)-1) 

结果

StringA Count SumA SumB 
47353  3  402 11351 
47355  1  21  482 

而且不要忘记;

DROP TABLE #TableName 
1

派生表版本。非常方便的方式来避免输入复杂的聚合函数两次:

select StringA, count(*), sum(ValueA) SumA, sum(ValueB) SumB 
from 
(
    select left(StringA, 5) StringA, ValueA, ValueB 
    from tablename 
) 
group by StringA 

ANSI SQL兼容! (除LEFT,应该是substring(StringA from 1 for 5)。)

0

下面的查询将提供所需的输出: -

select distinct substring(stringA,1,charindex('-',StringA)-1) StringA, 
Count(StringA) over (partition by substring(stringA,1,charindex('-',StringA)-1)) Count, 
sum(ValueA) over (partition by substring(stringA,1,charindex('-',StringA)-1)) SumA, 
sum(ValueB) over (partition by substring(stringA,1,charindex('-',StringA)-1)) SumB 
from test 

输出: -

StringA Count SumA SumB 
47353  3  402 11351 
47355  1  21  482 
相关问题