在這個例子中,你給你根本不需要連接。我希望,這是一個真實的例子,而不是人爲的。你想做的事情在這裏很簡單,你根本不需要連接,你不需要row_number。你可以這樣說:
select id,Username,Fullname from Users
UNION ALL
select id,Username,Fullname from GrobUsers
where id not in (select id from Users)
UNION ALL
select id,Username,Fullname from FrobUsers
where id not in (select id from Users) and id not in (select id from GrobUsers)
,它會給你:
id Username Fullname
----------- ---------- -----------------
7 iboyd Ian Boyd
8 nicholle Nicholle Kuzniak
9 chris Chris Windibank
10 jamie Jamie Bellaire
(4 row(s) affected)
下面是測試情況下,我用:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Users]') AND type in (N'U'))
DROP TABLE [dbo].[Users]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GrobUsers]') AND type in (N'U'))
DROP TABLE [dbo].[GrobUsers]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FrobUsers]') AND type in (N'U'))
DROP TABLE [dbo].[FrobUsers]
GO
CREATE TABLE [dbo].[Users](
[Id] [int] NOT NULL,
[Username] [nchar](50) NULL,
[Fullname] [nchar](50) NULL,
CONSTRAINT [PK_Users] 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
CREATE TABLE [dbo].[GrobUsers](
[Id] [int] NOT NULL,
[Username] [nchar](50) NULL,
[Fullname] [nchar](50) NULL,
CONSTRAINT [PK_GrobUsers] 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
CREATE TABLE [dbo].[FrobUsers](
[Id] [int] NOT NULL,
[Username] [nchar](50) NULL,
[Fullname] [nchar](50) NULL,
CONSTRAINT [PK_FrobUsers] 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
INSERT INTO Users Values (7,'iboyd','Ian Boyd')
INSERT INTO Users Values (8,'nicholle','Nicholle Kuzniak')
INSERT INTO Users Values (10,'jamie','Jamie Bellaire')
INSERT INTO [GrobUsers] Values (7,'iboyd','Ian Alexander Boyd ')
INSERT INTO [GrobUsers] Values (8,'nicholle','Nicholle Bachand')
INSERT INTO [GrobUsers] Values (9,'chris','Chris Windibank')
INSERT INTO [FrobUsers] Values (7,'iboyd','Ian')
INSERT INTO [FrobUsers] Values (9,'nicholle','Chris W.')
INSERT INTO [FrobUsers] Values (10,'jamie','James Bellaire')
GO
我還沒有得到關於開發工具這臺計算機沒有嘗試過,但是你可以使用'CROSS APPLY'然後使用'ROW_NUMBER'重新分區,並且返回ROW_NUMBER爲1的行嗎? – 2011-06-10 21:28:59