SQL分组和总和

时间:2012-02-01 18:15:26

标签: sql sql-server-2005

我想知道如何从我当前的结果集中获取以下结果集。

我的查询是这样的:

SELECT SUBSTRING(Col1, 1, 3) As 'Series', b.Col2, cast(c.Price * c.Qty as money) AS Total
from tableName a
inner join ....
...
WHERE date between '1/1/2012' and '1/31/2012'
AND B IN ('C50', 'C51', 'C52', 'C53', 'C54')
GROUP BY Col1, b.Col2, c.Price, c.Qty

并返回此结果集:

Series       Col2        Total
----------   ----------  ----------
105          C50         5.00
105          C50         15.00
105          C53         20.00
105          C53         20.00
105          C53         20.00

这就是我希望它的工作方式:

Series       Col2        Total
----------   ----------  ----------
105          C50         20.00
105          C53         60.00

谢谢

3 个答案:

答案 0 :(得分:1)

只需对未聚合的列进行分组,例如:

SELECT SUBSTRING(Col1, 1, 3) As 'Series', b.Col2, 
    sum(cast(c.Price * c.Qty as money)) AS Total
from tableName a
inner join ....
...
WHERE date between '1/1/2012' and '1/31/2012'
AND B IN ('C50', 'C51', 'C52', 'C53', 'C54')
GROUP BY Col1, b.Col2

答案 1 :(得分:0)

这很容易。仅使用Col1Col2作为分组标准进行分组,并总结您的表达式CAST(c.Price * c.Qty as money)

SELECT 
   SUBSTRING(Col1, 1, 3) As 'Series', 
   b.Col2, 
   SUM(CAST(c.Price * c.Qty as money)) AS Total
FROM tableName a
inner join ....
...
WHERE date between '1/1/2012' and '1/31/2012'
AND B IN ('C50', 'C51', 'C52', 'C53', 'C54')
GROUP BY Col1, b.Col2

答案 2 :(得分:0)

按计算列分组:SUBSTRING(Col1, 1, 3)

SELECT sub.Series, sub.Col2, SUM(sub.Total)
FROM
(
SELECT SUBSTRING(Col1, 1, 3) As 'Series', b.Col2, cast(c.Price * c.Qty as money) AS Total
from tableName a inner join ....
  ...
WHERE date between '1/1/2012' and '1/31/2012'
  AND B IN ('C50', 'C51', 'C52', 'C53', 'C54') 
) as sub
GROUP BY sub.Series, sub.Col2