在SQL Server 2005中显示UNION语句的每一列

时间:2012-02-10 07:18:35

标签: sql sql-server sql-server-2005

我有这些简单的SQL语句:

SELECT     COUNT(ID) AS Expr1
FROM         Table1
UNION
SELECT     COUNT(ID) AS Expr2
FROM         Table1 AS Table1_1
WHERE     (UPDATED > CREATED)
UNION
SELECT     COUNT(DISTINCT DATEPART(year, UPDATED)) AS Expr3
FROM         Table1 AS Table1_2

我想将结果显示为:

Expr1     Expr2    Expr3
-----     -----    -----
5           3         2

怎么做?我了解UNION比在OR子句中使用WHERE更可靠,更快。

2 个答案:

答案 0 :(得分:5)

你不能用UNION执行此操作 - 这将为您提供行的联合 - 而不是列。

根据您的要求,尝试这样的事情:

SELECT 
    Expr1 = (SELECT COUNT(ID) FROM Table1),
    Expr2 = (SELECT COUNT(ID) FROM Table1 WHERE UPDATED > CREATED),
    Expr3 = (SELECT COUNT(DISTINCT DATEPART(year, UPDATED)) FROM Table1)

这将为您提供一行包含三列,包含您正在寻找的值。

答案 1 :(得分:2)

不像

SELECT 
COUNT(ID) AS Expr1,
    (SELECT COUNT(ID) FROM Table1 WHERE UPDATED > CREATED) as Expr2,
    COUNT(DISTINCT DATEPART(year, UPDATED) as Expr3
FROM Table1

你需要什么?