DB是SQL Server 2008
表A:
'标识符'列中的值:A,B,C,D,E,F “余额”列中的值:10,100,30,50,70,55
期望的结果集:
'Identifier_New'列中的值:Z,Y,X 总和(余额)栏中的值:40,170,105
总和余额的逻辑映射:
标识符A和C的总和和组余额为Z. 标识符B和E的总和和组余额为Y. 标识符D和E的总和和组余额为X.
我可以在单个sql中获得上述所需的结果集吗?
由于
答案 0 :(得分:3)
试试这个:
SELECT x.v AS Identifier_New, SUM(Balances)
FROM mytable
CROSS APPLY (SELECT CASE Identifier
WHEN 'A' THEN 'Z'
WHEN 'C' THEN 'Z'
WHEN 'B' THEN 'Y'
WHEN 'E' THEN 'Y'
WHEN 'D' THEN 'X'
WHEN 'F' THEN 'X'
END ) AS x(v)
GROUP BY x.v
答案 1 :(得分:1)
SELECT CASE WHEN Identifier = 'A' or Identifier = 'C' THEN 'Z'
WHEN Identifier = 'B' or Identifier = 'E' THEN 'Y'
WHEN Identifier = 'D' or Identifier = 'F' THEN 'X'
END AS [Identifier_New],
SUM(Balances) AS [Sum of Balances]
FROM TABLE A
GROUP BY CASE WHEN Identifier = 'A' or Identifier = 'C' THEN 'Z'
WHEN Identifier = 'B' or Identifier = 'E' THEN 'Y'
WHEN Identifier = 'D' or Identifier = 'F' THEN 'X'
END