0

您好,我有下表:

USE [dm]
GO

/****** Object:  Table [dbo].[Demo]    Script Date: 12/12/2012 08:09:31 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Demo](
    [File] [nvarchar](50) NULL,
    [version] [nchar](10) NULL,
    [label] [nchar](10) NULL
) ON [PRIMARY]

GO

--option A
INSERT INTO [dbo].[Demo]
VALUES (N'123.doc', N'1', NULL)
INSERT INTO [dbo].[Demo]
VALUES (N'123.doc', N'2', NULL)
INSERT INTO [dbo].[Demo]
VALUES (N'123.doc', N'3', N'A')
INSERT INTO [dbo].[Demo]
VALUES (N'123.doc', N'4', NULL)
INSERT INTO [dbo].[Demo]
VALUES (N'123.doc', N'5', N'B')
GO 

我需要创建一个查询或可能的新输出表或视图,如下所示(注意新列 CalcVersion)。知道如何在不使用编程语言的情况下做到这一点吗?

File    version    label   CalcVersion
123.doc 1           NULL   A.1
123.doc 2           NULL   A.2
123.doc 3           A      A.3   
123.doc 4           NULL   B.1
123.doc 5           B      B.2

另一种可能的情况是:

option B
INSERT INTO [dbo].[Demo]
VALUES (N'123.doc', N'1', N'A')
INSERT INTO [dbo].[Demo]
VALUES (N'123.doc', N'2', NULL)
INSERT INTO [dbo].[Demo]
VALUES (N'123.doc', N'3', NULL)
INSERT INTO [dbo].[Demo]
VALUES (N'123.doc', N'4', N'B')

在这种情况下,结果应该是:

File    version   label   CalcVersion
123.doc 1           A      A.1         
123.doc 2           NULL   B.1
123.doc 3           NULL   B.2
123.doc 4           B      B.3 

请指教。谢谢你。

4

1 回答 1

0

我想我去:

 UPDATE demo set ver =(
      (SELECT TOP 1 label FROM demo t WHERE t.[file] = pt.[file] 
      and cast(t.[version] as int) > cast(pt.[version] as int) 
            AND t.label is NOT NULL 
       ORDER BY pt.[version] asc)) from demo pt
where pt.label is NULL;

然后将其与等级连接如下:

    select *,     ver + '.' + cast(RANK() over (partition by [file] order by version asc) as 
varchar(10)) as ver from demo where label is null;
于 2012-12-13T02:31:46.927 回答