C# SQL数据透视表中的行和列之和

C# SQL数据透视表中的行和列之和,c#,sql,pivot,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

结果是:

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
我想添加计数为1、2和3的列 并添加包含每行总和的列 并为每个列的末尾添加一行。
请帮助我。

与汇总一起使用如何

c_melli            1     2   3
0015601218  720000  400000  NULL
5099572650  490000  NULL    NULL
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

我通常建议人们在报告工具、网页或任何数据去向的地方进行总结。如果没有严格定义记录顺序,那么很容易将总行与详细行混合在一起

但你想要的是可能的,这里有一个方法:

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

免责声明:我是从内存中执行此操作的,尚未对其进行测试。

以及动态获取cost_教师列和每个列的计数的解决方案????@user3527426哦,我误解了您的问题,认为您需要的是总和而不是记录计数。但我看到有人能给你一个解决方案。
;
-- 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