我需要像运行余额或总计一样运行VoucherNo连接..将前一个VoucherNo连接到当前的VoucherNo行,如图所示
查询是:
select
v.VoucherDate,v.VoucherNo,v.VoucherType,v.Narration,SUM(v.Debit) Debit , SUM(v.Credit) Credit,dbo.GetBalance(v.CompanyProfileId,v.AccountCode,v.VoucherDate ,SUM(v.Debit), SUM(v.Credit)) Balance
from AcVoucher v
where v.VoucherDate Between '2016-03-24' and '2016-03-30' and v.CompanyProfileId = 2 and v.AccountCode = '05010001'
group by v.VoucherNo,v.VoucherDate,v.VoucherType,v.Narration,v.CompanyProfileId,v.AccountCode
架构:
GO
/****** Object: Table [dbo].[AcVoucher] Script Date: 03/30/2016 3:47:02 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AcVoucher](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[CompanyProfileId] [int] NOT NULL,
[AccountCode] [nvarchar](50) NOT NULL,
[VoucherNo] [bigint] NOT NULL,
[VoucherType] [nvarchar](5) NOT NULL,
[VoucherDate] [datetime] NOT NULL,
[Narration] [nvarchar](500) NULL,
[Debit] [float] NOT NULL,
[Credit] [float] NOT NULL,
[TaxPercentage] [float] NULL,
[DiscountPercentage] [float] NULL,
[CreatedBy] [int] NULL,
[CreatedDate] [datetime] NULL,
CONSTRAINT [PK_ACVoucher_1] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
答案 0 :(得分:0)
您可以使用与SQL Server中字符串连接基本相同的逻辑来执行此操作。唯一的区别是where
子句。
一个关键问题是连接的排序。这在问题中并不明显,因此我在查询中添加了minid
,并使用(以相反的顺序)选择要汇总的ID:
with v as (
select v.VoucherDate, v.VoucherNo, v.VoucherType, v.Narration,
SUM(v.Debit) as Debit , SUM(v.Credit) as Credit,
dbo.GetBalance(v.CompanyProfileId, v.AccountCode, v.VoucherDate,
SUM(v.Debit), SUM(v.Credit)
) as Balance,
min(id) as minid
from AcVoucher v
where v.VoucherDate Between '2016-03-24' and '2016-03-30' and
v.CompanyProfileId = 2 and v.AccountCode = '05010001'
group by v.VoucherNo, v.VoucherDate, v.VoucherType,v.Narration, v.CompanyProfileId, v.AccountCode
)
select v.*,
stuff((select ',' + cast(v2.VoucherNo as varchar(8000))
from v v2
where v2.minid >= v.minid
for xml path ('')
), 1, 1, '') as RunningConcat
from v;