从存储的procdedure中分组结果集

时间:2017-04-12 16:45:47

标签: sql-server tsql stored-procedures group-by

我在设置存储过程时遇到问题,以便返回的数据按特定方式分组以便进行报告。我想对非合同部门的结果集进行分组,并且非合同部门的每个分组都会从每个合同部门显示其下面的相关数据。如果特定合同部门不存在某一行,我仍然希望显示合同部门的值为0.

供参考,非合约部门包括(B,D,E,F,G,H,J,K,L,M,V),合约部门包括(C,O,T,NHQ,National)。我能够通过传入ID参数来实现所需的分组,因此结果集用于单个非合同分部,但我需要能够通过适当的分组一次性返回所有非合同分部。

The result set should look similar to this

一些DDL和测试数据:

CREATE TABLE [dbo].[RcmpDivision]
(
    [ID] [int] PRIMARY KEY IDENTITY(1,1) NOT NULL,
    [DivisionName] [varchar](50) NOT NULL,
    [IsContractDivision] [bit] NOT NULL
)

CREATE TABLE [dbo].[DivisionalTransaction]
(
    [ID] [int] PRIMARY KEY IDENTITY(1,1) NOT NULL,
    [FiscalYearID] [int] NOT NULL,
    [ToDivisionID] [int] NOT NULL,
    [FromDivisionID] [int] NOT NULL,
    [IsRmCredit] [bit] NOT NULL
)

ALTER TABLE [dbo].[DivisionalTransaction]
WITH CHECK ADD CONSTRAINT [FK_DivisionalTransaction_RcmpDivision]
FOREIGN KEY([ToDivisionID]) REFERENCES [dbo].[RcmpDivision] ([ID])

ALTER TABLE [dbo].[DivisionalTransaction] CHECK CONSTRAINT [FK_DivisionalTransaction_RcmpDivision]

ALTER TABLE [dbo].[DivisionalTransaction]
WITH CHECK ADD  CONSTRAINT [FK_DivisionalTransaction_RcmpDivision1]
FOREIGN KEY([FromDivisionID]) REFERENCES [dbo].[RcmpDivision] ([ID])

ALTER TABLE [dbo].[DivisionalTransaction] CHECK CONSTRAINT [FK_DivisionalTransaction_RcmpDivision1]

INSERT INTO [dbo].[RcmpDivision]
       ([DivisionName],
       [IsContractDivision])
VALUES
('B',0),('C',1),('D',0),('E',0),('F',0),('G',0),('H',0),('J',0),('K',0),
('L',0),('M',0),('National',1),('NHQ',1),('O',1),('T',1),('V',0)

INSERT INTO [dbo].[DivisionalTransaction]
       ([FiscalYearID]
       ,[ToDivisionID]
       ,[FromDivisionID]
       ,[IsRmCredit])
VALUES
(1,7,14,1),(1,4,14,1),(1,9,14,1),(1,7,14,1),(1,4,14,0),(1,7,12,1),(1,9,14,1),(1,3,4,0),
(1,3,4,0),(1,4,14,1),(1,3,1,0),(1,3,12,0),(1,9,2,0),(1,7,2,1),(1,5,15,1),(1,9,16,0),
(1,5,2,1),(1,10,13,1),(1,5,8,0),(1,5,13,1),(1,9,4,0),(1,1,2,1),(1,1,12,1),(1,1,12,1),
(1,1,12,1),(1,1,15,1),(1,1,15,1)

1 个答案:

答案 0 :(得分:0)

我不能确定您的问题,但我假设您的非合同分部记录中的ID列将与ToDivisionID列上的DivisionalTransaction列相关联{1}}表(基于我从种子数据中可以看出的内容)。

根据这一假设,一种快速简便的方法是将所有非合同部门与您的合同部门交叉加入,外部加入DivisionalTransation,然后使用以下总和函数生成数:

select ncd.DivisionName, cd.DivisionName, 
    sum(case when dt.ID is null then 0 else 1 end) as TotalCount
from dbo.RcmpDivision as ncd
cross join dbo.RcmpDivision as cd
left outer join dbo.DivisionalTransaction as dt
on dt.FromDivisionID = cd.ID
    and dt.ToDivisionID = ncd.ID
where cd.IsContractDivision = 1
    and ncd.IsContractDivision = 0
group by ncd.DivisionName, cd.DivisionName
order by ncd.DivisionName, cd.DivisionName

Here's the result from the given seed data

只需将此查询存入您的存储过程,您应该好好去