具有相同列值SQL SERVER的结果集中多行的SUM值

时间:2016-12-01 08:55:53

标签: sql tsql

来自此查询



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

如果它与子查询有关,请简要说明放置子查询的位置。我并没有真正理解子查询,因为我理解了pythons和javascript中的循环。

2 个答案:

答案 0 :(得分: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

最简单的方法就是这个

答案 1 :(得分: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