2017-07-12 2 views
0

Erstellen zwei Tabellen Eltern und KindWie Punkte mit zwei Tabellen in SQL-Server zu summieren?

Create table parent (ID int, ParentId int,Text varchar(20)) 
Create table Child (child1Id int, ParentId int, point int) 

ID ParentId Text 
1  NULL  Sony 
2  1   phone 
3  2   sale 
4  2   Rate 

child1Id ParentIdId point 
100   3    10 
200   4    20 

ich so etwas wie dieses Ich Ausgabe wie folgt

Select sum(b.point),a.ParentId,a.Text from parent A join Child B on a.ID =b.ParentId group by a.ParentId,a.Text 

versucht benötigen.

ID ParentId Text Point 
1  NULL  Sony null 
2  1   phone 30 
+1

Wie über einige Beispieldaten? –

Antwort

1

Sie können dies tun mit einer Unterabfrage

SELECT p.ID 
    , p.parentId 
    , p.[Text] AS 'Text' 
    , cld.pointSum AS 'Point' 
FROM dbo.Parent AS p 
    LEFT JOIN (
     SELECT c.ParentId 
      , SUM(c.point) AS 'pointSum' 
     FROM dbo.Child AS c 
     GROUP BY c.ParentId 
    ) cld ON (p.ID = cld.ParentId)