我有这些简单的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
更可靠,更快。
答案 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
你需要什么?