我不是在寻找Distinct
解决方案。我认为这对我的情况不起作用。
我有3个表,如下所示:
表1
AccountNo, Date, Property, Ascores, Bscores
表2
AccountNo, Date, Property, Cscores
表3
AccountNo, Date, Property, Dscores, Escores
我想和他们一起加入他们。 AccountNo, Date, Property
应该重复Ascores, Bscores, Cscores, Dscores
& Escores
应归结为AccountNo, Date, Property
。
我在网上发现了很多资源,似乎相关子查询可能是一个解决方案,但我不知道怎么写。
任何人都可以帮助我,谢谢
我尝试了这个SQL代码:
SELECT
T1.AccountNo,
T1.[Date],
T1.Property,
SUM(T1.Ascores),
SUM(T1.Bscores),
SUM(T2.Cscores),
SUM(T3.Dscores),
SUM(T3.Escores)
FROM
Table1 T1
FULL OUTER JOIN
Table2 T2 ON T1.AccountNo = T2.AccountNo
FULL OUTER JOIN
Table3 T3 ON T1.AccountNo = T3.AccountNo
GROUP BY
T1.AccountNo, T1.[Date], T1.Property
然而输出是这样的:
这完全不是我想要的结果......
理想的输出应该是这样的:
答案 0 :(得分:0)
看来你的日期也包括时间。将日期转换为字符串以删除时间部分,仅包含yyyy / mm / dd部分。现在根据这个分组,那么你将获得每天不同的记录。
答案 1 :(得分:0)
尝试使用union all
:
select AccountNo, [Date], Property,
sum(Ascores) as Ascores,
sum(Bscores) as Bscores,
sum(Cscores) as Cscores,
sum(Dscores) as Dscores,
sum(Escores) as Escores
from ((select t1.AccountNo, t1.[Date], t1.Property, t1.Ascores, T1.Bscores,
0 as Cscores, 0 as Dscores, 0 as Escores
from table1 t1
) union all
(select t2.AccountNo, t2.[Date], t2.Property, 0 as Ascores, 0 as Bscores,
t2.Cscores, 0 as Dscores, 0 as Escores
from table2 t2
) union all
(select t3.AccountNo, t3.[Date], t3.Property, 0 as Ascores, 0 as Bscores,
0 as Cscores, t3.Dscores, t3.Escores
from table3 t3
) union all
) t
group by AccountNo, [Date], Property;
如果您的date
确实被声明为日期而不是其他类型,那么这并不能解释您所看到的差异。如果是其他任何类型,请使用cast([Date] as date)
和select
中的group by
。