2012-01-13 68 views
0

我创建一个选择查询与三个表的联合.... 这样与列标识符

select a as A,b as B c as C where c = x union 
select b as A,d as B e as C where e = y and d = a union 
select f as A,g as B,h as C 

和查询的结果SQL视图是这样的:

A B C 
=========== 
1 abc ... 
55 def ... 
1 sas ... 

所以我希望有一个列可以计算行数,只是为了防止重复标识符。 财产以后这样

Row A B C 
================ 
1 1 abc ... 
2 55 def ... 
3 1 sas ... 

....

我的问题是如何能够做到?

+2

看看'ROW_NUMBER()'在2008 – JonH 2012-01-13 21:20:12

+0

我尝试过,但我还没有看到它在工会上工作 – jcvegan 2012-01-13 21:21:21

+0

你关心你获得行的顺序是什么?如果“行”是一个整数,从1开始并运行到行数,您是否关心?如果没有,还有'NEWID()',这可能更容易在这里使用。 – hvd 2012-01-13 21:22:59

回答

3
CREATE VIEW dbo.vname 
AS 
    SELECT [Row] = ROW_NUMBER() OVER (ORDER BY A), A, B, C FROM 
    (<UNION query here>) AS x; 

更换为了通过与任何命令你”喜欢看到应用。请注意,您需要在外部查询中针对dbo.viewname使用ORDER BY来确保Row将按照该顺序出现。

+0

嘿,这工作很好。谢谢! – jcvegan 2012-01-13 21:35:33

5

您可以使用ROW_NUMBER()这样的:

SELECT ROW_NUMBER() OVER (ORDER BY A,B,C) AS RowNo, * 
FROM 
(
select a as A,b as B c as C where c = x 
union 
select b as A,d as B e as C where e = y and d = a 
union 
select f as A,g as B,h as C 
) x 
1

您可以使用公用表表达式来实现这一目标:

WITH unionTable 
AS 
(
    select a as A, b as B, c as C where c = x union 
    select b as A, d as B, e as C where e = y and d = a union 
    select f as A, g as B, h as C 
) 
SELECT ROW_NUMBER() OVER (ORDER BY A) AS RowNumber, * 
FROM unionTable