选择DISTINCT两个列并使另一个列的值相加

时间:2014-11-23 11:07:21

标签: sql sql-server-2008 sum distinct

给定两个链接在一起的表

tbl_Gasoline 
--------------
ID | Type
-------------
1  | Diesel
2  | Kerosene

tbl_Expense
-----------------------------
ID | Price  | GasolineType (tbl_Gasoline foreign key)
-----------------------------
1  | 5000   | 1
2  | 4000   | 2
3  | 3000   | 1

我想要像这样的输出

tbl_GasolineExpense
----------------------------
ID |  Price  | Type
----------------------------
1  |  8000   | Diesel
2  |  4000   | Kerosene

我曾尝试使用DISTINCT和SUM子句,但我似乎无法做出好的查询。 我使用SQL已经很久了,所以一些帮助真的很值得赞赏。

4 个答案:

答案 0 :(得分:1)

试试这个

SELECT e.id, SUM(price) AS 'price', g.NAME 
FROM tbl_expense e
INNER JOIN tbl_gasoline g ON e.GasolineType = g.id 
GROUP BY e.id, g.NAME

答案 1 :(得分:0)

请试一试。

SELECT
e.id,
SUM(price) AS 'price',
g. NAME
FROM
    tbl_expense e
INNER JOIN tbl_gasoline g ON e.GasolineType = g.id
GROUP BY
    g.id,g. NAME

答案 2 :(得分:0)

选择

g.ID,

E.SUM(PRICE)作为价格,

e.GasolineType

来自

tbl_Gasoline g,tbl_Expense e

其中

g.ID = e.GasolineType group by e.GasolineType

答案 3 :(得分:0)

SELECT tbl_Gasoline.ID,SUM(tbl_Expense.Price),tbl_Gasoline.Type 
from tbl_Expense inner join tbl_Gasoline on tbl_Expense.GasolineType = tbl_Gasoline.ID 
group by tbl_Gasoline.ID