2010-09-23 4 views
2

J'ai deux tables SQL Server 2005: MainTable et Orders.Générer un rapport à l'aide de SUM

maintable:

| MainID | Serial | 
------------------- 
| 1  | A00001 | 
| 2  | B00002 | 

Commandes:

| OrderID | MainID | Name | Value | 
----------------------------------- 
| 1  | 2  | John | 100 | 
| 2  | 2  | Mike | 200 | 
| 3  | 1  | John | 150 | 
| 4  | 1  | Mike | 350 | 
| 5  | 1  | John | 200 | 
| 6  | 2  | John | 500 | 
| 7  | 1  | Mike | 50 | 

Je veux obtenir quelque chose comme ceci:

|Serial | Name | Total | 
----------------------- 
| A00001 | John | 350 | 
| A00002 | John | 600 | 
| A00001 | Mike | 400 | 
| A00002 | Mike | 200 | 

Répondre

1
SELECT 
    m.serial, 
    o.name, 
    SUM(o.value) 
FROM 
    main m 
    INNER JOIN order o ON m.mainid = o.mainid 
GROUP BY 
    o.name, 
    m.serial 
+1

C'est le moyen de formater SQL! +1 – Teekin

+1

Merci! Cela fonctionne très bien .. – milo2010

1
select serial, name, sum(value) as total 
from maintable m inner join orders o on 
m.mainID = o.mainID 
group by 
serial, name 
1
SELECT 
M.SERIAL, O.NAME, SUM(VALUE) AS TOTAL 
FROM MAINTABLE M JOIN ORDERS O ON O.MAINID=M.MAINID 
GROUP BY M.SERIAL, O.NAME 
0

sélectionnez Série, nom, Total

de maintable m,

(sélectionnez MainID, nom, SUM (valeur) Total de commandes o groupe par MainID, Nom) O

où m. MainID = O.MainID

Questions connexes