从列到行的总金额

时间:2019-06-28 09:38:19

标签: sql sql-server tsql

我目前正在汇总货币数据类型的五列。列Amount2,Amount3,Amount4,Amount5必须显示为“行”,并相应显示其总和。

当前执行查询后的结果如下:

enter image description here

但是我需要以这种格式显示结果:

enter image description here

有人知道这样做的方法吗?

我确实尝试过此方法,但未能使其正常工作:

SELECT name, amount1, column
FROM
(
    select 
        Name,
        sum(Amount1) as Amount1,
        sum(Amount2) as Amount2,
        sum(Amount3) as Amount3,
        sum(Amount4) as Amount4,
        Sum(Amount5) as Amount5
    from 
        #temp
    group by
        Name
) d
UNPIVOT
(
  value
  for column in (Amount2,Amount3,Amount4,Amount5)
) unpiv;

我收到以下错误:

  

Msg 156,第15层,状态1,第54行   关键字“ FROM”附近的语法不正确。

     

第102层15级州立67行   'd'附近的语法不正确。

样本数据

Create table #temp
(
    Name varchar(10),
    Amount1 money,
    Amount2 money,
    Amount3 money,
    Amount4 money,
    Amount5 money 
)

insert into #temp
(
    Name,
    Amount1,
    Amount2,
    Amount3,
    Amount4,
    Amount5
)
SELECT
    'Test',
    1,
    NULL,
    NULL,
    4,
    NULL
UNION ALL
SELECT
    'Test1',
    1,
    NULL,
    NULL,
    NULL,
    5
UNION ALL
SELECT
    'Test2',
    1,
    NULL,
    3,
    NULL,
    NULL
UNION ALL
SELECT
    'Test',
    1,
    2,
    NULL,
    NULL,
    NULL

select 
    Name,
    sum(Amount1) as Amount1,
    sum(Amount2) as Amount2,
    sum(Amount3) as Amount3,
    sum(Amount4) as Amount4,
    Sum(Amount5) as Amount5
from 
    #temp
group by
    Name

drop table #temp

2 个答案:

答案 0 :(得分:1)

对于每种类型UNION ALL,您可以简单地使用Amount

; with cte as
(
    select *
    from   #temp
)
select 
    Name,
    sum(Amount1) as Amount1
from 
    cte
group by
    Name

union all

select  'Amount2', sum(Amount2) from cte

union all

select  'Amount3', sum(Amount3) from cte

union all

select  'Amount4', sum(Amount4) from cte

union all

select  'Amount5', sum(Amount5) from cte

答案 1 :(得分:0)

在SQL Server中,最简单(通常效率最高)的方法是apply

select v.*
from (select Name,
             sum(Amount1) as Amount1,
             sum(Amount2) as Amount2,
             sum(Amount3) as Amount3,
             sum(Amount4) as Amount4,
             sum(Amount5) as Amount5
      from #temp t
      group by Name
     ) n cross apply
     (values (Name, Amount1),
             ('Amount2', Amount2),
             ('Amount3', Amount3),
             ('Amount4', Amount4),
             ('Amount5', Amount5)
     ) v(Name, Amount)
where v.Amount is not null;
相关问题