如何在SQL Server中获取每列新记录的总和

时间:2015-07-31 14:26:07

标签: sql-server

我对SQL Server有疑问。我有一张这样的桌子:

productname |Level|  January  | Feburary | March | total
------------x-----x-----------x----------x-------x------
  Rin       | L1  |  10       | 20       |  30   | 60
  Rin       | L2  |  5        | 10       |  10   | 25
  Rin       | L3  |  20       | 5        |  5    | 30
  Pen       | L1  |  5        | 6        |  10   | 21 
  Pen       | L2  |  10       | 10       |  20   | 40
  Pen       | L3  |  30       |10        |  40   | 80

根据上面的表数据,我想要输出如下

productname |Level|  January  | Feburary | March | total
------------x-----x-----------x----------x-------x------
  Rin       | L1  |   10      | 20       |  30   | 60
  Rin       | L2  |   5       | 10       |  10   | 25
  Rin       | L3  |  20       | 5        |  5    | 30
  RinTotal  |All  |  35       | 35       |  45   | 115
  Pen       | L1  |  5        | 6        |  10   | 21 
  Pen       | L2  |  10       | 10       |  20   | 40
  Pen       | L3  |  30       | 10       |  40   | 80
  PenTotal  | All |  45       | 26       |  70   |141

我试过像下面的查询

SELECT productname
    ,LEVEL
    ,sum(january) AS January
    ,sum(Feburary) AS Feburary )
    ,Sum(march) AS March
    ,Sum(total) AS total
FROM test

UNION

SELECT *
FROM test

但没有给出确切的输出。请指出我如何在SQL Server中实现此任务的正确方向。

3 个答案:

答案 0 :(得分:0)

请试试这个:

SELECT * FROM TEST
UNION
SELECT PRODUCTNAME+'TOTAL','ALL' AS LEVEL,SUM(JANUARY)AS JANUARY,SUM(FEBURARY)AS FEBURARY),SUM(MARCH)AS MARCH,SUM(TOTAL)AS TOTAL
FROM TEST GROUP BY PRODUCTNAME

答案 1 :(得分:0)

这真的属于前端。通过大多数报告工具,组小计等通常非常简单。此外,不要懒惰并使用select *,您应该始终在列中显式。由于您有特定的订单,我添加了几个额外的列用于排序。

另外,不要害怕为查询添加一些空格和格式。它使您的生活更容易阅读和以后的调试。

我认为这样的事情应该让你接近。注意我改为UNION ALL。使用UNION时,它将排除重复项。由于您知道没有重复行的事实,UNION ALL将无需检查重复项。

select productname + 'Total' as productname
    , 'All' as level
    , sum(january) as January
    , sum(Feburary) as Feburary
    , Sum(march) as March
    , Sum(total) as total
    , productname as SortName
    , 1 as SortOrder
from test
group by productname

union ALL

select productname
    , level
    , January
    , Feburary
    , March
    , Total
    , productname as SortName
    , 0 as SortOrder
from test 
order by SortName, SortOrder

答案 2 :(得分:0)

我会使用Group by With Rollup执行此操作。有关详细信息check here

SELECT * 
FROM   (SELECT productname=productname + CASE WHEN level IS NULL THEN 'Total' 
                           ELSE '' END, 
               Level=Isnull(level, 'ALL'), 
               Sum(january)  AS January, 
               Sum(feburary) AS Feburary, 
               Sum(march)    AS March, 
               Sum(total)    AS total 
        FROM   Yourtable 
        GROUP  BY rollup ( productname, level )) a 
WHERE  productname IS NOT NULL 

SQLFIDDLE DEMO