列出范围和基于条件的总计数

时间:2016-07-30 18:43:04

标签: sql-server-2008-r2 sql-server-2014

表架构

CREATE TABLE [dbo].[TblMaster](
    [SID] [int] IDENTITY(1,1) NOT NULL Primary Key,
    [VID] [int] NOT NULL,
    [CreatedDate] [datetime] default (getdate()) NOT NULL,
    [CharToAdd] [varchar](10) NULL,
    [Start] [int]  NOT NULL,
    [End] [int] NOT NULL
)
GO

CREATE TABLE [dbo].[TblDetails](
    [DetailsID] [int] IDENTITY(1,1) NOT NULL Primary Key,
    [SID] [int] NOT NULL,
    [Sno] [int] NOT NULL,
    [ConcatenatedText] [varchar](20) NOT NULL,
    [isIssued] [bit] default (0) NOT NULL,
    [isUsed] [bit] default (0) NOT NULL
)
GO

示例数据:

Insert into dbo.TblMaster Values (1,default, 'CA', 1, 5)
Insert into dbo.TblMaster Values (1,default, 'PA', 1, 5)
GO
Insert into dbo.TblDetails values(1, 1, 'CA1', 0,0)
Insert into dbo.TblDetails values(1, 2, 'CA2', 0,0)
Insert into dbo.TblDetails values(1, 3, 'CA3', 0,0)
Insert into dbo.TblDetails values(1, 4, 'CA4', 1,0)
Insert into dbo.TblDetails values(1, 5, 'CA5', 0,0)
Insert into dbo.TblDetails values(2, 1, 'PA1', 0,0)
Insert into dbo.TblDetails values(2, 2, 'PA2', 0,0)
Insert into dbo.TblDetails values(2, 3, 'PA3', 1,0)
Insert into dbo.TblDetails values(2, 4, 'PA4', 0,0)
Insert into dbo.TblDetails values(2, 5, 'PA5', 0,0)
Insert into dbo.TblDetails values(3, 1, '1', 0,0)
Insert into dbo.TblDetails values(3, 2, '2', 1,0)
Insert into dbo.TblDetails values(3, 3, '3', 1,0)
Insert into dbo.TblDetails values(3, 4, '4', 0,0)
Insert into dbo.TblDetails values(3, 5, '5', 0,0)
    GO

预期输出:

enter image description here

我现在建立的查询:

Declare @VID INT  = 1

    ;WITH Tmp as
    (
      SELECT 
            TM.CharToAdd as Prefix, 
            sno,
            sno - ROW_NUMBER() OVER(ORDER BY sno) as grp
      FROM dbo.TblDetails TD
      LEFT JOIN dbo.TblMaster TM on TM.[SID] = TD.[SID]             
      WHERE isIssued = 0 and isUsed = 0 
            AND  TM.VID = @VID 
    )
    SELECT  Prefix,
            MIN(sno) as RangeStart,
            MAX(sno) as RangeEnd,
            COUNT(*) as [Count]
    FROM Tmp
    GROUP BY grp, Prefix

在TblDetails表中,想要查找位列为0的所有记录的可用值范围及其总计数。如果位列为1则表示已使用它,所以我试图跳过它并列出其余值作为可用记录。令人怀疑的是我是否能很好地解释问题陈述,因此提供了样本数据和预期输出以便更好地理解。我确实尝试过做一些递归函数,但结果与预期的输出不匹配。所以寻求帮助来解决这个问题。

1 个答案:

答案 0 :(得分:0)

你非常亲密......

<强> CODE

Declare @VID INT  = 1

;with cte as(
    select
        m.CHarToAdd,
        d.sno,
        d.sno - ROW_NUMBER() OVER(partition by m.CharToAdd ORDER BY sno) as grp
    from 
        TblMaster m
        inner join
            TblDetails d on
            d.sid = m.sid
    where
        d.isIssued = 0 and d.isUsed = 0 and m.vid = @VID)

select
    CharToAdd,
    min(sno) as Start,
    max(sno) as [End],
    (max(sno) - min(sno) + 1) as [Count]
from cte
group by
    CHarToAdd, grp
order by
    CHarToAdd

<强>结果

CharToAdd   Start   End Count
CA             1    3   3
CA             5    5   1
PA             1    2   2
PA             4    5   2