SQL数据透视表中行和列的总和

时间:2014-04-12 18:12:06

标签: c# sql pivot

price   c_melli cost_teacher
150000  5099572650  1         
170000  5099572650  1         
170000  5099572650  1         
150000  0015601218  1         
170000  0015601218  1         
200000  0015601218  1         
200000  0015601218  2         
200000  0015601218  2         
200000  0015601218  1   

select * from
(select * from temp) as s 
PIVOT
(
    SUM(price)
    FOR [cost_teacher] IN ([1],[2],[3])
) as p1

结果是:

c_melli            1     2   3
0015601218  720000  400000  NULL
5099572650  490000  NULL    NULL

我想添加计数为1和2和3的列 并添加每行总和的列 并添加一行到结尾以计算每列。 请帮帮我。

3 个答案:

答案 0 :(得分:1)

Select t.c_melli, s.[1], c.[1], s.[2], c.[2], s[3], c.[3], s.[1]+s.[2]+s.[3] as sumRow from (select distinct c_Melli from temp) t
inner join(
  select * from
  (select * from temp) as s 
  PIVOT
  (
    SUM(price)
    FOR [cost_teacher] IN ([1],[2],[3])
  ) as p1
) s on s.mellicode = t.mellicode
inner join(
  select * from
  (select * from temp) as s 
  PIVOT
  (
    Count(price)
    FOR [cost_teacher] IN ([1],[2],[3])
  ) as p1
) c on c.mellicode = t.mellicode

答案 1 :(得分:1)

我通常建议人们在报告工具或网页或数据的任何地方进行汇总。如果未严格定义记录顺序,则很容易将总线与细节线混合在一起。

但你想要的是什么,这是一种方法:

;
-- Turning the original query into a CTE allows us to easily re-use it in the query
with detail as (
  select c_melli
     ,   [1]
     ,   [2]
     ,   [3]      
  from
  (select * from temp) as s 
    PIVOT
   (
      SUM(price)
      FOR [cost_teacher] IN ([1],[2],[3])
   ) as p1
)
-- The first SELECT retrieves the detail pivoted row, plus a calculated total of all columns.
select  c_melli
   ,    [1]
   ,    [2]
   ,    [3]
   ,    row_total = COALESCE([1],0) + COALESCE([2],0) + COALESCE([3],0)
from  detail
-- using "union all" rather than "union" because "union all" skips the
-- duplicate-removal step (which we don't need) and is therefore faster.
union all 
-- The section SELECT summarizes all of the detail rows.  
select 'total'  -- this assumes c_melli is a string; if not, use something else
  ,     SUM([1])
  ,     SUM([2])
  ,     SUM([3])
  ,     SUM(COALESCE([1],0) + COALESCE([2],0) + COALESCE([3],0))
from    detail

免责声明:我是从内存中做到的,并没有对其进行测试。

答案 2 :(得分:0)

如何使用WITH ROLLUP?

SELECT CASE WHEN (GROUPING(c_melli) = 1) THEN 'Total'
        ELSE ISNULL(c_melli, 'UNKNOWN')
   END as c_melli, 
   [1], [2], [3], [1]+[2]+[3] as Total 
FROM
  (select * from temp) as s 
PIVOT
(
  SUM(price)
  FOR [cost_teacher] IN ([1],[2],[3])
) as p1
GROUP BY c_melli WITH ROLLUP
相关问题