合并2个不相关查询的输出

时间:2014-09-04 10:13:37

标签: sql-server

我需要一次执行2个查询并在一个组合输出中生成结果。两个查询都只返回1行

查询1:

SELECT city, state FROM "Table1" WHERE Id = '123'

查询2:

select count(*) as colCount from "Table2" where name = "xyz"

输出格式:city, state, colCount

2 个答案:

答案 0 :(得分:0)

使用子查询:

SELECT city, state, 
       colCount = (SELECT count(*)
                   FROM Table2 
                   WHERE name = "xyz")
FROM Table1 
WHERE Id = '123'

子查询不能返回多行。但事实并非如上所述。您可以使用TOP 1来确保它,但如果它是例外,我会更喜欢例外。

答案 1 :(得分:0)

以下查询适合您:

SELECT city, state, 
       colCount = (SELECT count(*)
                   FROM Table2 
                   WHERE name = "xyz") as colCount
FROM Table1 
WHERE Id = '123'