如何将两个查询结果合并为一行?

时间:2014-12-01 22:02:08

标签: sql sql-server

我有两个查询,每个返回一个结果,即一个数字

Select Count(*) as StockCountA from Table_A where dept='AAA'

结果

StockCountA 
550

Select Count(*) as StockCountB from Table_B where dept='BBB'

结果

StockCountB 
450

我希望将这两个结果加入一行记录,即

| StockCountA | StockCountB    
| 550         | 450

4 个答案:

答案 0 :(得分:32)

您可以使用:

select
(Select Count(*) as StockCountA from Table_A where dept='AAA') as StockCountA,
(Select Count(*) as StockCountB from Table_B where dept='BBB') as StockCountB

说明:您可以选择单个值作为select语句中的字段,因此您可以编写类似

的内容
select
  x.*,
  (select Value from Table_Y y) as ValueFromY
from
  Table_X x

这仅适用于scalar queries,这意味着子查询应该只有1列,最多1行。如果0行,ValueFromY将返回NULL并且超过1行,则查询将失败。

select的另一个特性(在SQL Server,MySQL和其他人中)是你可以只选择值而不指定一个表,如下所示:

Select
  3.14 as MoreOrLessPI

通过编写如下所示的查询,您可以将这两个事实结合起来,将两个计数合并为一个结果:

Select
  (Select query that returns at most 1 row) as Result1,
  (Select another query that returns at most 1 row) as Result2

答案 1 :(得分:4)

这应该会给你想要的结果:

SELECT * FROM(
(Select Count(*) as StockCountA from Table_A where dept='AAA') StockCountA ,
(Select Count(*) as StockCountB from Table_B where dept='BBB') StockCountB
);

答案 2 :(得分:0)

尝试以下SQL:

select (Select Count(*) as StockCountA from Table_A where dept='AAA')  StockCountA, 
       (Select Count(*) as StockCountB from Table_B where dept='BBB')  StockCountB

希望这有助于:)

答案 3 :(得分:-1)

虽然并非总是最佳做法,但可以进行CROSS JOIN ..

SELECT
COUNT(Table_A.SOME_COLUMN) as StockCountA
,COUNT(Table_B.SOME_COLUMN) as StockCountB
FROM Table_A, Table_B WHERE Table_A.dept='AAA' AND Table_B.dept='BBB'