如何使用多个条件进行分组

时间:2014-05-04 17:18:25

标签: sql sql-server sql-server-2008

我有下表

Type    SubType value
A      1       1
A      2       2
A      3       3
A      4       4
B      1       1
B      2       2
B      3       3
C      1       1
C      2       2
C      3       3
C      4       4

我想按所有行进行分组,除非Type = A,输出应该在

之下
Type    Sum
A1    1
A2    2
A3    3 
A4    4
B     6
C     10

是否可以在一个条件下按几行分组,而在另一个条件下分组?

3 个答案:

答案 0 :(得分:3)

是的,您必须编写一个创建组定义的表达式:

Select case When Type = 'A' then type + ltrim(str(subtype, 9))
            Else Type End Type, Sum(Value) Sum
From table
Group By case When Type = 'A' then type + ltrim(str(subtype, 9))
            Else Type End

答案 1 :(得分:2)

是的,您可以GROUP BY CASE表达;

SELECT CASE WHEN type='A' 
            THEN type+CAST(subtype AS VARCHAR(MAX))
            ELSE type END [Type],
       SUM(value) [Sum]
FROM mytable
GROUP BY CASE WHEN type='A'
              THEN type+CAST(subtype AS VARCHAR(MAX))
              ELSE type END
ORDER BY [Type]

An SQLfiddle to test with

在SQL Server 2012中,您可以在不使用强制转换的情况下使用CONCAT,这会稍微简化查询。

答案 2 :(得分:1)

另一种选择。将逻辑分为两种情况:

SELECT Type + CAST(subtype AS VARCHAR(MAX)) AS Type,
       SUM(Value) AS Sum
FROM mytable
WHERE Type = 'A'
GROUP BY Type, Subtype

UNION ALL

SELECT Type,
       SUM(Value)
FROM mytable
WHERE Type <> 'A'
GROUP BY Type

ORDER BY Type ; 

SQL-Fiddle (thnx到@Joachim Isakkson)进行测试