主表
PrimaryID | SecondaryID | PrimaryTime | SecondaryTime
------------------------------------------------------
100 | 101 | 10 | 50
101 | 103 | 20 | 60
102 | 100 | 30 | 70
100 | 102 | 40 | 80
预期产出:
ID | Total TIME
-----------------
100 | 120
101 | 70
102 | 110
103 | 60
答案 0 :(得分:2)
这里我们只是从4列表中输出2列子查询,然后总结每个不同的主要或次要Id之前的值:
CREATE TABLE MainTable (PrimaryID int, SecondaryID int, PrimaryTime int, SecondaryTime int)
INSERT MainTable VALUES (100,101,10,50), (101,103,20,60), (102,100,30,70), (100,102,40,80)
;WITH MainCTE AS (
SELECT PrimaryID ID, PrimaryTime Time FROM MainTable
UNION ALL
SELECT SecondaryID ID, SecondaryTime Time FROM MainTable
)
SELECT ID, SUM(Time) [Total TIME] FROM MainCTE GROUP BY ID
这很简单,重点是找出你要求的东西。