给出以下查询
Select Count(*) From TableA
Select Count(*) From TableB
Select Count(*) From TableC
Select Count(*) From TableD
我想返回如下视图:
-----------
| Counts |
-----------
| 2 | --from TableA
-----------
| 3 | --from TableB
----------
| 4 | --from TableC
----------
| 5 | --from TableD
----------
我尝试使用UNION,例如:
CREATE VIEW [Foo]
AS
SELECT COUNT(*) AS [Counts]
FROM TableA
UNION
SELECT COUNT(*)
FROM TableB
UNION
SELECT COUNT(*)
FROM TableC
UNION
SELECT COUNT(*)
FROM TableD
但是订单不正确
-----------
| Counts |
-----------
| 2 | --from TableA
-----------
| 3 | --from TableB
----------
| 5 | --from TableD
----------
| 4 | --from TableC
----------
除了UNION之外,还有其他替代方法可以用来生成所需的结果集吗?
答案 0 :(得分:2)
非常接近,只需为您的订单添加一个派生字段。
CREATE VIEW [Foo]
AS
SELECT TOP(100) PERCENT
*
FROM
(
SELECT COUNT(*) AS [Counts], RowOrder=1
FROM TableA
UNION
SELECT COUNT(*), 2
FROM TableB
UNION
SELECT COUNT(*), 3
FROM TableC
UNION
SELECT COUNT(*), 4
FROM TableD
)AS X
ORDER BY RowOrder
OR-订单在计数视图之外。
CREATE VIEW [Foo]
AS
SELECT
*
FROM
(
SELECT COUNT(*) AS [Counts], RowOrder=1
FROM TableA
UNION
SELECT COUNT(*), 2
FROM TableB
UNION
SELECT COUNT(*), 3
FROM TableC
UNION
SELECT COUNT(*), 4
FROM TableD
)AS X
...
SELECT * FROM Foo ORDER BY RowOrder
答案 1 :(得分:1)
UNION
内部为您进行排序,您需要union all
或定义显式排序:
SELECT COUNT(*) AS [Counts]
FROM TableA UNION ALL
SELECT COUNT(*)
FROM TableB UNION ALL
SELECT COUNT(*)
FROM TableC UNION ALL
SELECT COUNT(*)
FROM TableD;
您还可以定义显式顺序:
SELECT COUNT(*) AS [Counts], 1 as SortOrder
FROM TableA UNION
SELECT COUNT(*), 2
FROM TableB UNION
SELECT COUNT(*), 3
FROM TableC UNION
SELECT COUNT(*), 4
FROM TableD;
因此,您需要在视图order by
中使用Foo
子句
select f.*
from Foo f
order by SortOrder;
答案 2 :(得分:1)
视图返回无序结果集。您可以尝试做:
create view v_counts as
select . . .
order by . . .
您将收到错误消息:
除非还指定了TOP,OFFSET或FOR XML,否则ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效。
正如消息所暗示的那样,有一种方法可以解决这个问题,但我建议不要这样做-即使您作弊,也不能保证视图会按顺序返回结果。 / p>
相反,请添加表名称:Select 'TableA' as which, Count(*) From TableA
union all
Select 'TableB' as which, Count(*) From TableB
union all
Select 'TableC' as which, Count(*) From TableC
union all
Select 'TableD' as which, Count(*) From TableD;