2016-07-30 76 views
2

表結構列表範圍和總計數基於條件

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,那麼這意味着它已經被使用,所以我試圖跳過它並列出其餘的可用記錄。懷疑我是否很好地解釋了問題陳述,提供了樣本數據和預期結果以便更好地理解。我曾嘗試做一些遞歸函數,但結果與預期輸出不匹配。所以尋求幫助來解決這個問題。

回答

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 
+0

感謝您的時間。 – prasanth

+0

@prasanth沒問題 – scsimon