在SQL中使用大小写并求和值

在SQL中使用大小写并求和值,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我已经开始使用SQL,但是我忘记了一些显示数据的方法。我有这样的桌子: drop table #temptable create table #temptable ( Id int, [Type] int, Balance numeric(10,2) ) INSERT INTO #TempTable (ID, [Type], Balance) values (103,1,500) INSERT INTO #TempTable (ID, [Type], Balance)

我已经开始使用SQL,但是我忘记了一些显示数据的方法。我有这样的桌子:

drop table  #temptable
create table #temptable
(
    Id int,
    [Type] int,
    Balance numeric(10,2)
)

INSERT INTO #TempTable (ID, [Type], Balance) values (103,1,500)
INSERT INTO #TempTable (ID, [Type], Balance) values (103,3,156)
INSERT INTO #TempTable (ID, [Type], Balance) values (103,4,790)
INSERT INTO #TempTable (ID, [Type], Balance) values (103,6,345)
INSERT INTO #TempTable (ID, [Type], Balance) values (103,1,450)
INSERT INTO #TempTable (ID, [Type], Balance) values (103,2,50)
INSERT INTO #TempTable (ID, [Type], Balance) values (104,1,100)
INSERT INTO #TempTable (ID, [Type], Balance) values (104,5,500)

select * from #temptable

我在临时表中有上述数据。结果查询应按ID分组,并在名为Type1Balance的一列中求和[Type]为1和3的余额,其余[Type]余额应在名为Type2Balance的另一列中求和。谁能帮我回答这个问题。提前感谢。

您可以使用基于类型的条件聚合

select id, 
sum(case when [Type] in (1,3) then Balance else 0 end) type1bal,
sum(case when [Type] not in (1,3) then Balance else 0 end) type2bal
from tablename
group by id

可以使用基于类型的条件聚合

select id, 
sum(case when [Type] in (1,3) then Balance else 0 end) type1bal,
sum(case when [Type] not in (1,3) then Balance else 0 end) type2bal
from tablename
group by id

谢谢,这工作非常好,但是我有一个问题,如果我们在select中有更多的字段,那么它将如何工作?您将必须对所有字段进行分组。或者将其作为子查询,并将其连接到
id
上所需的表中,以获取结果中无法分组的其他列。此查询需要我三个表,外部查询也需要再次连接以获取一些字段,因此可以在子查询和主查询中重复表吗?可以这样做谢谢,这很好,但是我有一个问题,如果我们在select中有更多的字段,那么它将如何工作?您必须对所有字段进行分组。或者将其作为子查询,并将其连接到
id
上所需的表中,以获取结果中无法分组的其他列。此查询需要我三个表,外部查询也需要再次连接以获取一些字段,因此可以在子查询和主查询中重复表吗?可以这样做那个