2011-12-20 24 views
0

我有兩個表。分組由不同表中的值

  • 第一個表列有:價格,code_one
  • 二表具有:code_one,code_two

兩個表可以使用code_one表進行連接。

如何獲得「由code_two分組的價格總和」?

我想:

Select sum(price) from table1 Group By (select a.code_two from table2 a, table1 b where a.code_one = b.code_one) 
+0

@OMG小馬:我試過有集團經過一個子查詢方...喜歡的東西:集團通過(從表2一,表1 a.code_two選擇b where b.code_one = a.code_two) – Nik 2011-12-20 05:00:30

回答

1
select code_two, SUM(price) 
from table1 t1 INNER JOIN table2 t2 ON t1.code_one = t2.code_one 
group by code_two 
+0

如果table1中存在where條件,該怎麼辦?就像說一個日期字段。所以我只想要一個特定的日期。是否正確:從table1中選擇code_two,SUM(price)t1 INNER JOIN table2 t2 ON t1.code_one = t2.code_one其中t1.date ='somedate'group by code_two ??? – Nik 2011-12-20 05:07:01

+0

是的,這是正確的 – Nighil 2011-12-20 05:08:03

+0

Nighil說,是的,這是正確的。 – Zohaib 2011-12-20 05:09:29

0
select sum(price) 'Price' from firsttable inner join secondtable on firsttable.code_one = secondtable.code_one 
group by secondtable.code_two