我在SQL Server中有以下表格:
Name1 Name2 Amount
Larry George 1
Larry Michael 1
Michael George 1
Michael Larry 1
Larry George 1
George Larry 1
如果有人能为我提供一个获得以下结果的脚本(这个名字无关紧要,例如拉里/乔治=乔治/拉里),那就太棒了:
Name_combination Amount
Larry / George 3
Larry / Michael 2
Michael / George 1
非常感谢提前
答案 0 :(得分:1)
当Name1为<时,您可以将Name1与Name2连接起来比Name2,或Name2与Name1否则:
SELECT
CASE WHEN Name1<Name2 THEN Name1 + ' / ' + Name2
ELSE Name2 + ' / ' + Name1 END AS Name_combination,
SUM(Amount) AS Amount
FROM
tablename
GROUP BY
CASE WHEN Name1<Name2 THEN Name1 + ' / ' + Name2
ELSE Name2 + ' / ' + Name1 END