汇总表中的所有对行

时间:2018-11-08 11:15:27

标签: sql sql-server tsql

我需要sql查询,该查询求和表中所有可能的原始对。

我的桌子看起来像这样:

ID  | Name | Value
1   |  A   | 100
2   |  B   | 150
3   |  C   | 250
4   |  D   | 600

在这种情况下,查询输出应为:

FistName  | SecondName | Sum
     A    |  B         | 250
     A    |  C         | 350
     A    |  D         | 700
     B    |  C         | 400
     B    |  D         | 750
     C    |  D         | 850

4 个答案:

答案 0 :(得分:4)

尝试一下:

select 
    t1.Name as FirstName,
    t2.Name as SecondName,
    t1.Value+t2.Value as Sum
from yourtable as t1
inner join yourtable as t2 on (t1.ID<t2.ID)

答案 1 :(得分:2)

仅基于l.ID < r.ID的条件进行INNER JOIN。这样可以确保该行不与自身连接,并且不会以1, 22, 1的形式重复:

DECLARE @t TABLE (ID INT, Name VARCHAR(100), Value INT);
INSERT INTO @t VALUES
(1, 'A', 100),
(2, 'B', 150),
(3, 'C', 250),
(4, 'D', 600);

SELECT l.Name FirstName, r.Name SecondName, l.Value + r.value [Sum]
FROM @t AS l
INNER JOIN @t AS r ON l.ID < r.ID
ORDER BY FirstName, SecondName

答案 2 :(得分:0)

这是一种可行的方法:

CREATE TABLE #T (ID INT, Name VARCHAR (10), VALUE INT)
INSERT INTO #T VALUES (1, 'A', 100), (2, 'B', '150'), (3, 'C', 250), (4, 'D', 600)

SELECT CASE WHEN T.Name < T2.Name THEN (T.Name + T2.Name)  
          ELSE (T2.Name + T.Name) 
      END AS FullName,
      SUM (T.Value) AS TotalValue
FROM #T AS T
FULL OUTER JOIN #T AS T2 ON T.Name <> T2.Name
GROUP BY CASE WHEN T.Name < T2.Name THEN (T.Name + T2.Name)  
            ELSE (T2.Name + T.Name)  END

答案 3 :(得分:-1)

通过cross join运算符使用很少使用的笛卡尔联接的机会:

select left.Name, right.Name, left.Value + right.Value as Sum
from DataTable left
  cross join DataTable right
order by left.Name, right.Name;

注意,如果输入表很大,则会导致很多行。为了避免将行和行本身合并在一起(出现{A,B}和{B,A},出现{A,A})条件。