我在下面有2张桌子。 公共列为ObjectId。
表1 :
Year ObjectId G_Amount
===== ======== ========-
2010 1234 5.00
2010 1234 5.00
2010 5678 10.00
2010 5678 20.00
2010 5678 50.00
2012 9101 0.00
2012 1122 70.00
2012 1122 100.00
表2 :
ObjectId I_Amount
========= ===========-
1234 10.00
1234 30.00
5678 15.00
5678 20.00
9101 25.00
9101 35.00
1122 10.00
1122 0.00
我想加入上面2个表,以便结果集如下所示。应该按年份显示G_Amount
(表1中每年的g_amount
总数)和I_Amount
(表2中每年的i_amount
总数)。
结果集:
Year G_Amount I_Amount
===== ======== ========-
2010 90.00 75.00
2012 170.00 70.00
有人可以帮忙吗?
答案 0 :(得分:2)
您的数据模型允许对象ID在多年内出现。因此,相关的表2条目将被相乘,即被添加到这些年的每一年。如果您不想这样做,则需要一个单独的表,每个对象一个记录。
同样,您将仅按年份和对象ID汇总第一个表,而仅按对象ID汇总第二个表。然后加入并再次聚合以获得年份。
select
t1.year,
sum(t1.totalg) as total_g_amount,
coalesce(sum(t2.totali), 0) as total_i_amount
from
(
select Year, ObjectId, sum(G_Amount) as totalg
from table1
group by Year, ObjectId
) t1
left join
(
select ObjectId, sum(i_Amount) as totali
from table2
group by ObjectId
) t2 on t2.ObjectId = t1.ObjectId
group by t1.year
order by t1.year;
答案 1 :(得分:1)
类似的方法适用于您的数据集。我为LEFT JOIN
中所有不在Table1
中的值添加了Table2
:
SELECT
T1.[Year]
, SUM(T1.G_Amount_Total) G_Amount
, ISNULL(SUM(T2.I_Amount_Total), 0) I_Amount
FROM
(
SELECT
[Year]
, ObjectId
, SUM(G_Amount) G_Amount_Total
FROM Table1
GROUP BY
[Year]
, ObjectId
) T1
LEFT JOIN
(
SELECT
ObjectId
, SUM(I_Amount) I_Amount_Total
FROM Table2
GROUP BY ObjectId
) T2
ON T1.ObjectId = T2.ObjectId
GROUP BY T1.[Year]
我确实看到您的数据结构存在一些潜在问题,例如,Year
中没有Table2
引用,但是,如果您的数据受到控制,则应该全部解决。
答案 2 :(得分:0)
尝试一下,无论如何,我还是T-SQL的新手,所以可能是错误的。
Select DISTINCT T1.Year
SUM (T1.G_Amount) as G_Amount,
SUM (T2.I_Amount) AS I_Amount
from table1 T1 join Table2 T2 on T1.ObjectID = T2.ObjectID