我有下表
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
是否可以在一个条件下按几行分组,而在另一个条件下分组?
答案 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]
在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)进行测试