在UNION ALL结果集中使用聚合函数

时间:2013-07-09 11:42:40

标签: sql sql-server tsql

如何在UNION ALL Resultset中使用聚合函数

例如

SELECT A,B FROM MyTable
UNION ALL
SELECT B,C FROM MYAnotherTable

结果集

    A  B
--------------
    1  2
    3  4
    4  5
    6  7

当我尝试获取MAX(A)时,它会返回3。我想要6

当我尝试获取MAX(B)时,它会返回4。我想要7

Max()以外,我可以获得另一个用户定义的聚合函数吗?

例如:

SELECT TOP 1 A WHERE B=5

真实案例Here

3 个答案:

答案 0 :(得分:3)

尝试这种方式:

select max(A)
from(
      SELECT A,B FROM MyTable
      UNION ALL
      SELECT B,C FROM MYAnotherTable
    ) Tab

SQL小提琴DEMO

如果列A是varchar(您在下面的评论中说过),请尝试这种方式:

select max(A)
from(
      SELECT cast(A as int) as A,B FROM MyTable
      UNION ALL
      SELECT B,C FROM MYAnotherTable
    ) Tab

使用TOP 1

select max(A)
from(
      SELECT top 1 cast(A as int) as A,B FROM MyTable
      UNION ALL
      SELECT B,C FROM MYAnotherTable
    ) Tab

答案 1 :(得分:0)

试试这个

DECLARE @a TABLE (a int, b int)
INSERT @a 
VALUES (1,2), (3,4)
DECLARE @b TABLE (b int, c int)
INSERT @b 
VALUES (4, 5),(6,7)

;WITH cte AS (
    SELECT A,B FROM @a
    UNION ALL
    SELECT B AS A,C AS B FROM @b
) SELECT MAX (a), MAX(b)

FROM cte

答案 2 :(得分:0)

CREATE TABLE    #Transaction (
                TransactionID INT, 
                ProductID INT, 
                TransactionDate datetime
)
INSERT INTO     #Transaction (
                TransactionID, 
                ProductID,
                TransactionDate
)
SELECT          TransactionID, 
                ProductID,
                TransactionDate
FROM            [Production].[TransactionHistoryArchive]
UNION
SELECT          TransactionID, 
                ProductID,
                TransactionDate
FROM            [Production].[TransactionHistory]