日期:2014-05-19  浏览次数:20523 次

一个主从表查询的问题
我有主从表如下:
tbMain
Id,Name,Date

tbChild
Id,MainId,Amount1,Amount2

想提取:
MainId,MainName,Date,sum(Amount1),sum(Amount2)
该怎么写

就是主表中的字段加上跟该主表ID对应的从表的sum和,作为一条记录。

MainId,MainName,Date,sum(Amount1),sum(Amount2)
1               啊             2009-1-1       55               100
2               啊1           2009-1-1       155               2100
3               啊2           2009-1-1       535               2100

------解决方案--------------------
select tbMain.* , t.Amount1 , t.Amount2 from tbMain
left join
(
select id , sum(Amount1) Amount1,sum(Amount2) Amount2 from tbChild group by id
) t
on tbmain.id = t.id

------解决方案--------------------
select
a.id MainID,
a.Name MainName,
a.Date MainDate,
SUM(Amount1) [sum(Amount1)],
SUM(Amount2) [sum(Amount2)]
FROM tbMain a
INNER JOIN tbChild b
ON a.id=b.id
GROUP BY a.id,a.Name,a.Date


select
a.id MainID,
a.Name MainName,
a.Date MainDate,
s1 [sum(Amount1)],
s2 [sum(Amount2)]
FROM tbMain a
INNER JOIN
(
SELECT ID,SUM(AMOUNT1) s1,SUM(AMOUNT2) s2
FROM tbChild b
GROUP BY ID
) b

ON a.id=b.id

随手敲的,可能有手误
------解决方案--------------------

select
A.[ID],
A.[Name],
A.[date],
sum(Amount1) AS [sum(Amount1)],
sum(Amount2) as [sum(Amount2)]
from tbMain as A
inner join tbChild as B on A.id=B.MainID
group by A.[ID],A.[Name],A.[date]