2010-09-23 196 views
2

我有兩個SQL Server 2005表:MainTable和Orders。使用SUM生成報告

MainTable:

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

訂單:

| 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 | 

我想是這樣的:

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

回答

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

這是格式化SQL的方式! +1 – Teekin 2010-09-23 20:19:35

+1

謝謝!它工作得很好.. – milo2010 2010-09-23 20:21:22

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

選擇串行,名稱,總

從MainTable米,

(選擇MainID,名稱,SUM(值)從訂單O基團總共由MainID,名稱)O

其中m。 MainID = O.MainID