2016-12-01 81 views
0

從這個查詢SUM值的值SQL SERVER

SELECT t1.type, t2.name, sum(t3.num) AS number, min(t1.price) AS price 
 
FROM t1 
 
JOIN t2 
 
t1.soandso = t2.soandso 
 
JOIN t3 
 
ON t2.soandso = t3.soandso 
 
GROUP BY t1.type, t2.name, t1.price

我得到的結果是

type name number price 
 
type1 name1 25  1 
 
type1 name1 35  1 
 
type1 name2 50  1 
 
type2 name3 15  1 
 
type2 name3 25  1 
 
type2 name4 25  1

我想能夠輸出

type name number price 
type1 name1 60  1 
type1 name2 50  1 
type2 name3 40  1 
type2 name4 25  1 

如果有事情做與子查詢,請註明所發生的事情,你放置子查詢的簡要說明。我不是很瞭解子查詢,就像我理解python和javascript中的循環一樣。

+1

扣除了價格。 – jarlh

回答

0
;with cte as (SELECT t1.type, t2.name, t3.num, t1.price 
FROM t1 
JOIN t2 
t1.soandso = t2.soandso 
JOIN t3 
ON t2.soandso = t3.soandso) 
SELECT type, name, sum(num) AS number, min(price) AS price 
from cte 
GROUP BY type, name 

簡單的方法是從GROUP BY這個

+0

會引發一個錯誤... – jarlh

+0

什麼是錯誤將增加 –

+1

第二個選擇總結中的總和是多少? – Roger

0
SELECT t1.type, t2.name, sum(t3.num) AS number, t1.price AS price 
FROM t1 
JOIN t2 ON t1.soandso = t2.soandso 
JOIN t3 ON t2.soandso = t3.soandso 
GROUP BY t1.type, t2.name, t1.price