我有像这样的查询的输出
Acct# OwnerType TotalBal Type1Bal Type2Bal Type3Bal
--------------------------------------------------------------
1234 Type1 0 1000 0
1234 Type2 0 0 1000
1234 Type3 0 0 0 1000
123456 Type1 0 2000 0 0
123456 Type2 0 0 2000 0
123456 Type3 0 0 0 2000
这是查询生成的示例数据。对于每个帐号,我需要一个标题行(类似这样的行),总行余额与实际上只有三个余额之一的行。任何人都可以建议或指出我正确的方向吗?
Acct# OwnerType TotalBal Type1Bal Type2Bal Type3Bal
-------------------------------------------------------------------
1234 TotalAmt 1000 0 0 0
1234 Type1 0 1000 0 0
1234 Type2 0 0 1000 0
1234 Type3 0 0 0 1000
123456 TotalAmt 2000 0 0 0
123456 Type1 0 2000 0 0
123456 Type2 0 0 2000 0
123456 Type3 0 0 0 2000
答案 0 :(得分:0)
Declare @Table table (Acct int,OwnerType varchar(25),TotalBal int,Type1Bal int,Type2Bal int,Type3Bal int)
Insert into @Table values
(1234 ,'Type1', 0, 1000, 0 , null),
(1234 ,'Type2', 0 , 0 , 1000, null),
(1234 ,'Type3', 0 , 0 , 0 , 1000),
(123456 ,'Type1', 0 , 2000 , 0 , 0 ),
(123456 ,'Type2', 0 , 0 , 2000 , 0),
(123456 ,'Type3', 0 , 0 , 0 , 2000)
Select Acct,OwnerType='TotalAmt',TotalBal=max(Type1Bal),Type1Bal=0,Type2Bal=0,Type3Bal=0 From @Table Group By Acct
Union All
Select Acct,OwnerType,TotalBal=0,Type1Bal=isnull(Type1Bal,0),isnull(Type2Bal,0),IsNull(Type3Bal,0) from @Table
Order By Acct,OwnerType
返回
Acct OwnerType TotalBal Type1Bal Type2Bal Type3Bal
1234 TotalAmt 1000 0 0 0
1234 Type1 0 1000 0 0
1234 Type2 0 0 1000 0
1234 Type3 0 0 0 1000
123456 TotalAmt 2000 0 0 0
123456 Type1 0 2000 0 0
123456 Type2 0 0 2000 0
123456 Type3 0 0 0 2000