Output我有以下表格输出 - 我拥有的内容:
Account No Description Seg1 Seg2 Seg3 Budget PeriodBalance
000-1120-00 Cash 000 1120 00 $1,000.00 $2,000.00
000-1130-00 Asset 000 1130 00 $1,500.00 $3,000.00
我想拥有什么:
Account No Description Seg1 Seg2 Seg3 Budget PeriodBalance
000-1120-01 Cash 000 1120 01 $500.00 $1,000.00
000-1120-02 Cash 000 1120 02 $500.00 $1,000.00
000-1130-00 Asset 000 1130 00 $1,500.00 $3,000.00
在这里,如果Seg2等于1120,那么我想将其拆分为2个帐户,后面是帐号No 01和02代替00中的段3,如上所示'我想干什么'部分。
declare @period int;
declare @year int
Select @period = 12, @year = 2017
Select
rtrim(c.Actnumbr_1) +'-'+ rtrim(c.Actnumbr_2)+ '-'+ rtrim(c.Actnumbr_3) as ACTNUMST,
c.ACTDESCR,
c.ACTNUMBR_1,
c.ACTNUMBR_2,
c.ACTNUMBR_3,
sum(a.PERDBLNC) as Period_Balance,
b.BUDGETAMT
from GL00100 c
left outer join GL11110 a on c.ACTINDX = a.ACTINDX
Left outer join
(Select
actindx,
sum(budgetamt) as budgetamt
from GL00201
where BUDGETID = 'budget2017'
and periodid <= @period group by actindx) b
on c.ACTINDX = b.ACTINDX
where
a.PERIODID <= @period and
a.year1 = @year
--and c.ACTINDX in ('18','211')
group by
c.ACTDESCR, c.ACTNUMBR_1, c.ACTNUMBR_2, c.ACTNUMBR_3, a.year1,c.ACTINDX,b.BUDGETAMT
答案 0 :(得分:0)
我不知道第二个查询是关于什么的,但是,使用此示例数据:
IF OBJECT_ID('tempdb..#yourtable') IS NOT NULL DROP TABLE #yourTable;
CREATE TABLE #yourtable
(
[Account No] varchar(20),
[Description] varchar(20),
Seg1 char(3),
Seg2 smallint,
Seg3 varchar(5),
Budget money,
PeriodBalance money
);
INSERT #yourTable
VALUES ('000-1120-00', 'Cash', '000', 1120, '00', $1000.00, $2000.00),
('000-1130-00', 'Asset','000', 1130, '00', $1500.00, $3000.00);
你可以这样做:
SELECT
[Account No] = SUBSTRING([Account No], 1, CHARINDEX('-', [Account No], CHARINDEX('-', [Account No])+1))+ordinal,
[Description],
Seg1, Seg2,
Seg3 = ordinal,
Budget = Budget / 2,
PeriodBalance = PeriodBalance / 2
FROM @yourTable
CROSS JOIN (VALUES ('01'), ('02')) split(ordinal)
WHERE Seg2 = 1120
UNION ALL
SELECT [Account No], [Description], Seg1, Seg2, Seg3, Budget, PeriodBalance
FROM @yourTable
WHERE Seg2 <> 1120;
...返回:
Account No Description Seg1 Seg2 Seg3 Budget PeriodBalance
---------------------- -------------------- ---- ------ ----- --------------------- ---------------------
000-1120-01 Cash 000 1120 01 500.00 1000.00
000-1120-02 Cash 000 1120 02 500.00 1000.00
000-1130-00 Asset 000 1130 00 1500.00 3000.00