我正在使用三个表的联合创建一个选择查询.... 像这样
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
,查询结果如下:
A B C
===========
1 abc ...
55 def ...
1 sas ...
所以我希望有一个列数来计算行数,只是为了防止重复标识符。 这样的事情
Row A B C
================
1 1 abc ...
2 55 def ...
3 1 sas ...
...
我的问题是如何做到这一点?
答案 0 :(得分: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 :(得分:3)
CREATE VIEW dbo.vname
AS
SELECT [Row] = ROW_NUMBER() OVER (ORDER BY A), A, B, C FROM
( <UNION query here> ) AS x;
将ORDER BY A替换为您希望应用的任何顺序。请注意,您需要在针对dbo.viewname的外部查询上使用ORDER BY,以保证Row将按此顺序出现。
答案 2 :(得分: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